父母将状态传递给孩子-React JS

时间:2018-12-05 21:16:57

标签: javascript reactjs

ObjectList有一个对象数组,这些对象被呈现为列表。当用户单击列表项时,该对象将发送回ObjectEditor,以便用户可以查看并继续编辑。问题在于我不确定如何将该对象传递给ObjectEditor,因为click事件是在ObjectList中发生的。

我最初的解决方案是将其作为道具传递给ObjectEditor并使用componentWillReceiveProps方法更新ObjectEditors的状态。但是,该解决方案不切实际,因为我不希望每次道具更改时都进行更新。有更好的方法吗?

我是React的新手,所以在介绍React之前,我现在避免使用Redux。

为了清楚起见,我已经大量削减了代码。

ObjectList:

      constructor(props){
       super(props);
       this.state = { objects: [
          {title: '', items: [], anotherThing:''},
          {title: '', items: [], anotherThing:''}
        ]}
      }

      viewObject = (index) => {
      let object = {...this.state.object[index]};
     // Then some code that passes the object to the ObjectEditor Component
       }

      render(){
        return(
          <div>

           <li key={index} onClick={ () => this.viewObject(index) } >
           // A list of titles from state
           </li>

          <ObjectEditor />
          </div>
        )
      }

ObjectEditor:

       constructor(props){
       super(props);
       this.state = {title:'', items: [], anotherThing:''}
       }

    // various event handlers that update the state based off form inputs

      render(){
        return(
          <div> 

            // Various form fields which get pushed to state

            <button>Save & Add New</button> 

            // function that maps through state and renders it to the page
          </div>
        )
      }
    }

1 个答案:

答案 0 :(得分:2)

我的建议是让父组件处理所有状态和逻辑,并使ObjectEditor组件成为没有逻辑或状态的简单表示组件。看起来像这样。

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            objects: [
                { title: '', items: [], anotherThing: '' },
                { title: '', items: [], anotherThing: '' }
            ],
            editObject: {},
        }
    }

    viewObject = (index) => {
        let object = { ...this.state.object[index] };
        this.setState({editObject: object}); // sets the state if the clicked item.
        // Then some code that passes the object to the ObjectEditor Component
    }

    handleChange = (e) => {
        // handle change
    }

    render() {
        return (
            <div>

                <li key={index} onClick={() => this.viewObject(index)} >
                // A list of titles from state
                </li>

                <ObjectEditor viewObject={this.state.viewObject} handleChange={this.handleChange} />
            </div>
        )
    }
}


class ObjectEditor extends React.Component {
    render() {
        return (
            // render some sort of editor
            // display data based on the props passed down
            // when user edits in the form, call up to the parent's change handler
        );
    }
}