【问题标题】:React Share variables between componentsReact 在组件之间共享变量
【发布时间】:2016-05-14 18:41:04
【问题描述】:

我有三个组件。 App 是父组件。 工具和绘图板是子组件。 我想在工具和绘图板组件之间传输数据。

export default class App extends  Component{
  getFormData(name, value){
   //empty so far
}
 render(){
   return(
    <div className="main-container">
        <DrawingBoard  styledata={???} />
        <Tools  data={this.getFormData.bind(this)}/>
   </div>
  );
}

我将函数 getFormData 作为属性传递给 Tools 以获取其数据。 现在我想传递名称和值,最好作为关联数组或对象 使用 arr["name"] = value 作为绘图板的属性。 我该怎么做?

【问题讨论】:

    标签: reactjs properties components


    【解决方案1】:

    您可以在App 组件中使用state,您可以在Tools 中更改它,并将新的state 传递给DrawingBoard

    class App extends React.Component {
      constructor() {
        super();
    
        this.state = {
          styledata: {}
        };
      }
    
      getFormData(name, value) {
        this.setState({
          styledata: { [name]: value }
        })
      }
    
      render() {
        return <div className="main-container">
          <DrawingBoard styledata={ this.state.styledata } />
          <Tools data={ this.getFormData.bind(this) } />
        </div>
      }
    }
    
    class Tools extends React.Component {
      getData() {
        // Load data
        // 
        this.props.data('color', 'red');
      }
    
      render() {
        return <div>
          <button onClick={ this.getData.bind(this) }>Change Data</button>
        </div>
      }
    }
    
    class DrawingBoard extends React.Component {
      render() {
        return <div>
          <h1 style={ this.props.styledata }>DrawingBoard</h1>
        </div>
      }
    }
    

    Example

    【讨论】:

    • 使用 this.getData.bind(this) 会直接降低应用程序的性能,因为它会重新渲染组件,因此使用 'this.getData = this,getData.bind(this)' in构造函数。欲了解更多信息,请访问'youtube.com/…'
    猜你喜欢
    • 2020-03-14
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 2022-10-12
    • 2020-11-08
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多