chi*_*nds 10 javascript reactjs
我试图从父组件中调用存储在子组件中的函数.但不确定要这样做.我知道如果是父母的形式孩子,我可以简单地使用组件道具,但不知道如何从父母到孩子.
正如您在下面的示例中看到的那样,父类中的按钮需要触发子类中的显示功能.
var Parent = React.createClass ({
render() {
<Button onClick={child.display} ?>
}
})
var Child = React.createClass ({
getInitialState () {
return {
display: true
};
},
display: function(){
this.setState({
display: !this.state.display
})
},
render() {
{this.state.display}
}
})
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最简单方法是使用refs.
var Parent = React.createClass ({
triggerChildDisplay: function() {
this.refs.child.display();
},
render() {
<Button onClick={this.triggerChildDisplay} />
}
})
var Child = React.createClass ({
getInitialState () {
return {
display: true
};
},
display: function(){
this.setState({
display: !this.state.display
})
},
render() {
{this.state.display}
}
})
Run Code Online (Sandbox Code Playgroud)
我基本上复制了你的例子,但请注意,在你的Parent中,我没有看到你渲染一个Child组件,但通常,你会,并且在那个Child上你会给它一个ref,比如<Child ref="child" />.
| 归档时间: |
|
| 查看次数: |
3761 次 |
| 最近记录: |