React 子组件监听父组件传递的值的变化

想让父组件的状态更新的时候。子组件也根据这个状态更新

父组件中
this.state = {
    checked: false
};
<Checkbox checked={checked}>Checkbox</Checkbox>
子组件中

当props发生变化时执行,初始化render时不执行,在这个回调函数里面,你可以根据属性的变化,通过调用this.setState()来更新你的组件状态,旧的属性还是可以通过this.props来获取,这里调用更新状态是安全的,并不会触发额外的render调用

//props发生变化时触发
componentWillReceiveProps(props) {
	console.log(props)
    this.setState({show: props.checked})
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React 中,可以通过 props 将数据从组件传递组件。如果组件的数据发生变化,可以通过 setState 方法更新组件的状态,并将新的状态传递组件组件可以通过 componentWillReceiveProps 方法监听组件传递过来的新的 props ,并根据新的进行相应的变化。 以下是一个示例代码: ```javascript // 组件 class ParentComponent extends React.Component { constructor(props) { super(props); this.state = { value: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(e) { this.setState({ value: e.target.value }); } render() { return ( <div> <input value={this.state.value} onChange={this.handleChange} /> <ChildComponent inputValue={this.state.value} /> </div> ); } } // 组件 class ChildComponent extends React.Component { constructor(props) { super(props); this.state = { outputValue: '' }; } componentWillReceiveProps(nextProps) { if (nextProps.inputValue !== this.props.inputValue) { this.setState({ outputValue: nextProps.inputValue }); } } render() { return <div>{this.state.outputValue}</div>; } } ``` 在这个示例中,组件中的 input 组件发生变化时,会触发 handleChange 方法,更新组件的 value 状态。同时,也会将新的 value 传递组件 ChildComponent。当组件接收到新的 inputValue 时,会触发 componentWillReceiveProps 方法,更新组件的 outputValue 状态。因此,当组件的 value 发生变化时,组件的内容也会随之变化

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值