我接近让它发挥作用。希望有人可以帮助我。
我有2个React文件。一个是Container
,另一个是Nav
组件。
在我的容器组件_template.js
中,我导入了一个模态npm包。我在此容器文件中创建了一个showModal
函数,我试图访问Nav
组件。
这是我到目前为止所收到的错误Uncaught TypeError: Cannot read property 'modal' of undefined
_template.js:
import React from 'react';
import { Link } from 'react-router';
import { prefixLink } from 'gatsby-helpers';
import { config } from 'config';
import Headroom from 'react-headroom';
import Nav from './nav.js';
import '../css/main.scss';
import Modal from 'boron/DropModal';
const modalStyle = {
minHeight: '500px',
backgroundColor: '#303841'
};
const backdropStyle = {
backgroundColor: '#F6C90E'
};
const contentStyle = {
backgroundColor: '#303841',
padding: '3rem'
};
export default class RootTemplate extends React.Component {
static propTypes = {
location: React.PropTypes.object.isRequired,
children: React.PropTypes.object.isRequired,
}
static contextTypes = {
router: React.PropTypes.object.isRequired,
}
constructor() {
super();
}
showModal () {
this.refs.modal.show();
}
render() {
return (
<div>
<Headroom>
<Nav showModal={this.showModal}/>
</Headroom>
<Modal ref="modal" modalStyle={modalStyle} contentStyle={contentStyle} backdropStyle={backdropStyle}>
<form>
<label>Name:</label>
<input type="text"/>
<label>Email:</label>
<input type="email"/>
<label>Message:</label>
<input type="text-area"/>
<input type="submit" placeholder="Submit" />
</form>
</Modal>
{this.props.children}
</div>
);
}
}
我的Nav.js文件:
import React from 'react';
import { Link } from 'react-router';
import { prefixLink } from 'gatsby-helpers';
import { Nav, NavGroup, NavItem, NavToggle, Icon } from 're-bulma';
export default class nav extends React.Component {
static propTypes = {
name: React.PropTypes.string,
};
constructor(props) {
super(props);
}
render() {
return (
<div>
<Nav>
<NavGroup align="left">
<NavItem>
<Link to={prefixLink('/')}>
<h2>Dillon Raphael</h2>
</Link>
</NavItem>
</NavGroup>
<NavToggle />
<NavGroup align="right" isMenu>
<NavItem>
</NavItem>
<NavItem>
</NavItem>
<NavItem>
<a href="#" onClick={::this.props.showModal}>Let's Work!</a>
</NavItem>
</NavGroup>
</Nav>
</div>
);
}
}
请注意<a href="#" onClick={::this.props.showModal}>Let's Work!</a>
这是我尝试调用从_template.js
文件传递下来的showModal函数的地方。
答案 0 :(得分:1)
添加到您的构造函数中,在_template.js文件中输入以下代码:
this.showModal = this.showModal.bind(this);
然后构造函数应如下所示:
constructor(props) {
super(props);
this.showModal = this.showModal.bind(this);
}