请帮助我获取反应组件中的元素状态或其他一些自定义功能以及我需要的信息。每个td标签都包含反应组件Block1。
下面的简化代码结构class Block2 extends React.Component {
render() {
return (
<table>
<tbody>
<tr>
<td>
<Block1 />
</td>
<td>
<Block1 />
</td>
</tr>
</tbody>
</table>
)}}
Block1 - 反应包含div元素的组件。 Block2位于组件Block3内。如何通过单击某个按钮从Block3获取Block1的状态? 现在,我可以获得Block1的列表,可能会看到道具,但我看不到状态。或者我可以获得DOM td元素并查看子类classNames(我在各州寻找)但我看不到道具......
答案 0 :(得分:1)
除非您使用像Redux这样的库,否则您必须执行以下操作来解决您的问题:
将状态存储在Block3
内,而不是Block1
。然后将任何将此状态更改为props
的{{1}}到Block3
的函数传递给Block2
。如果在Block1
中发生任何更改,请调用此函数。模式应该是:
Block1
如果您确实想要访问父组件中的子class Block3 {
changeState(value) {
this.setState({ stateValue: value });
}
render() {
return (
<Block2 changeState={this.changeState}/>
)
}
}
class Block2 extends React.Component {
render() {
return (
<table>
<tbody>
<tr>
<td>
<Block1 changeState={this.props.changeState} />
</td>
<td>
<Block1 changeState={this.props.changeState} />
</td>
</tr>
</tbody>
</table>
)}}
class Block1 {
changeHandler(ev) {
this.props.changeState(ev.target.value);
}
render() {
return (
<button onClick={this.changeHandler}/>
)
}
}
,请考虑使用state
:
refs
编辑:看到你的代码后我的解决方案:
class Block2 {
render() {
return <Block1 ref={ (childComponent) => { this.block1Child = childComponent; } } />;
// Now you may use this.block1Child to access child component's state eg: this.block1Child.setState({})
}
}