簡體   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