class Template extends React.Component {
constructor(props) {
super(props)
this.state = {
isMenuVisible: false,
isVideoModelVisible: false,
loading: 'is-loading'
}
this.handleToggleVideoModel = this.handleToggleVideoModel.bind(this)
}
handleToggleVideoModel() {
alert('test handleToggleVideoModel ');
console.log('layout');
this.setState({
isVideoModelVisible: !this.state.isVideoModelVisible
})
}
render() {
const { children } = this.props
return (
{children()}
)
}
}
Template.propTypes = {
children: React.PropTypes.func,
handleToggleVideoModel: React.PropTypes.func
}
export default Template
在{children()}的“上方模板”文件中呈现的pages / index.js
class HomeIndex extends React.Component {
constructor(props) {
super(props);
this.handleToggleVideoModel = this.handleToggleVideoModel.bind(this)
}
render() {
return (
<div>
<Helmet>
<title>{siteTitle}</title>
<meta name="description" content={siteDescription} />
</Helmet>
<Banner onToggleVideoModel=
{this.props.handleToggleVideoModel}/>
)
}
}
HomeIndex.propTypes = {
onToggleVideoModel: React.PropTypes.func
}
export default HomeIndex
components / Banner.js
const Banner = (props) => (
<section id="banner" className="major">
<li><a href="javascript:void(0);" className="button next" onClick=
{props.onToggleVideoModel}>Watch video</a></li>
</section>
)
export default Banner
我该怎么做? 我想从Banner.js调用handleToggleVideoModel,它是layout / index的大子级Parent布局/index.js。 子页面/index.js 孙子组件/Banner.js 我受困于此,任何人都知道如何从Banner访问handleToggleVideoModel会为我提供解决方案。
答案 0 :(得分:0)
从组件1向组件2传递方法引用,如下所示:
<Component 2 toggle={this.handleToggleVideoModel}/>
现在再次将此引用传递给组件2这样的组件4
<Component 4 toggle={this.props.handleToggleVideoModel} />
现在您可以像这样从组件4调用此函数:
this.props.handleToggleVideoModel