【发布时间】:2018-07-08 23:44:18
【问题描述】:
我现在使用 reactjs 已经有一段时间了,到目前为止效果非常好。然而,有一件事我有点卡住了。我试图在单击时更改父组件的状态,但前提是子组件具有某个类,否则不会。
让我在这里为您提供一个代码示例:
父组件:
class Parent extends React.Component{
constructor(){
super();
this.state = {
pageState: false
}
}
changeState(){
this.setState({pageState: !this.state.pageState});
}
render(){
return(
<div id="app">
<ul>
<Child sendState={this.changeState.bind(this)} heading="Home"/>
<Child sendState={this.changeState.bind(this)} heading="About"/>
<Child sendState={this.changeState.bind(this)} heading="Contact"/>
<Child sendState={this.changeState.bind(this)} heading="Work"/>
</ul>
</div>
)
}
}
render(<Parent/>, document.getElementById("app-wrapper"));
子组件
class Child extends React.Component{
render(){
return(
<li className="list_element">
<div className="card_block" onClick={this.props.sendState.bind(this)}>
<h2>{this.props.heading}</h2>
</div>
<li>
)
}
}
所以基本上我想要实现的是,当点击“li”内的卡片时,状态需要改变,但前提是父“li”有一个“当前”类。所以点击卡片元素,检查它的类,如果它有“当前”类,改变状态。
有没有办法让这成为可能?
【问题讨论】:
-
您可以尝试将回调函数作为道具传递给孩子。 codementor.io/ryan286/…
-
您的意思是,在单击 div 时,您需要检查
ul的类或组件<Parent />吗? -
只创建另一个状态,指示父级是否具有'当前'状态。然后在子节点的 onClick 方法中,只有父节点处于“当前”状态时才调用
this.props.sendState。 -
好吧,点击
- 里面的
我需要检查- 是否有当前类,如果有,改变状态,那么有没有办法通过“ className”属性到“stateChange”函数?我的意思是如果可以做到,那么这个函数可以检查被点击的元素或其父元素是否具有“当前”类,如果是,则更改状态,否则不要更改...
- 里面的
标签: reactjs