我是react的新手,我不知道如何从父组件更改子组件状态。下面是代码
<ChildComponent productCode={this.state.productCode} />
我希望在父组件的productCode
上执行setState
时,子组件接收productCode
。
从父组件发布一个事件并在子组件中订阅该事件是我的头等大事。
有什么建议吗?
这是有效的,但请注意Child
将此数据作为prop接收,而不是作为其内部state
的一部分。
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
render() {
return (
<section>
Count: {this.state.count}
<br />
<button
onClick={() =>
this.setState((prevState) => ({
count: prevState.count + 1,
}))
}
>
Increment Count
</button>
<Child passedCount={this.state.count} />
</section>
);
}
}
class Child extends React.Component {
render() {
return (
<section>
I am the child. The <code>count</code> * 2 ={' '}
{/* Access `this.props.passedCount` to use the value */}
<b>{this.props.passedCount * 2}</b>
</section>
);
}
}
const rootElement = document.getElementById('root');
ReactDOM.render(<Parent />, rootElement);
section {
background: beige;
padding: 1em;
}
section > section {
background: sandybrown;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
假设childState
是你的子状态,如果你正在使用类组件,你必须在你的类中添加一个componentWillReceiveProps
钩子生命周期。
componentWillReceiveProps(nextProps) {
this.setState({ childState: nextProps.productCode});
}
您正好遇到了人们使用状态容器的原因。我只能建议尝试redux、mobx或mobx-state-tree。
如果你真的不想深入研究这些工具,事情会变得有点棘手,如果你坚持的话,你可以这样做,但我建议不要这样做。
这样做:首先在父组件中编写一个函数来改变它的状态,然后将该函数交给子组件,然后在子组件中调用该函数。下面是一个代码示例,您可能会稍微摆弄一下:
// the parent
function parent() {
const [state, setState] = useState('')
const update = () => {
setState("new state")
}
return(<Child updateFunction={update} />)
}
// the cild
function Child(props) {
return(
<FancyComponent
onClick={props.update}
/>
)
}