采取2个组成部分:
ParentComponent ChildComponent
ParentComponent在render中设置ChildComponent:
render() {
return (
<ChildComponent x='default value' />
)
}
然后,ParentComponent希望将x ='default value'更改为'hello',可能是为了响应onClick事件。
我想我的困惑是,我知道如何设置初始变量x,但不知道以后如何更改。
您可以在Parent
状态中对此进行管理,然后将状态值作为道具传递给Child
。
子组件。
const ChildComponent = props => {
return <div>{props.x}</div>;
};
父组件
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
x: "default value"
};
}
changeX = x => {
this.setState({
x: x
});
};
render() {
return (
<div>
<ChildComponent x={this.state.x} />
<button
onClick={() => {
this.changeX("x");
}}
>
Change X
</button>
</div>
);
}
}
这是codepen。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句