繁体   English   中英

如何在 React.js 的另一个组件中更新组件状态变量的值?

[英]How to update the value a component's state variable in another component in React.js?

我想在第二个类中更新 'change_color' 的值,并在值更改时自动在第一个类中呈现它。 假设,'Second' 组件是'First' 组件的子组件。

解决了。 代码已编辑,这就是答案。

class First extends Component {
  constructor() {
     super();
     this.state = {
       change_color: false
     }
     this.handleChange = this.handleChange.bind(this);
  }
  handleChange() {
    this.setState({
       change_color: true
    })
  }
  render() {
   console.log(this.state.change_color);
   return(<div><Second colorChange={this.handleChange} /></div>)
  }
}

class Second extends Component {
  constructor() {
     super();
  }
  render() {
    return(<div><button onClick={this.props.colorChange} /></div>)
  }
}

你需要做的是提升状态。 创建一个新组件,该组件具有带有颜色和更改颜色功能的状态。 然后将相应的属性作为道具传递给第一个和第二个组件,并在它们内部调用函数来改变颜色。 有道理吗?

或许你可以试试这个,只做一个容器组件,把你想改变的值设置成容器组件的一个状态,添加一个改变状态值的方法,然后,你可以使用“this.props.handleColorChange”来在子组件中调用父组件的方法。

 class ParentComponent extends Component { constructor() { super(); this.state = { change_color: false } } handleColorChange= () => { const {change_color} = this.state; this.setState = { change_color: !change_color } } render() { const {change_color} = this.state, {handleColorChange} = this; return ( <div> <ChildComponent1 color={change_color} handleColorChange={handleColorChange} /> <ChildComponent2 color={change_color} handleColorChange={handleColorChange} /> </div> ); } } class ChildComponent1 extends Component { constructor() { super(); } render() { const {color} = this.props; return( <span>now, the color is {color}</span> ) } } class ChildComponent2 extends Component { constructor() { super(); } const {handleColorChange} = this.props; return( <button onClick={handleColorChange}>click to change color</button> ) }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM