如何在Reactjs中将道具从父组件传递到子组件

时间:2019-07-15 09:22:36

标签: javascript arrays reactjs state

我需要合并两个组件数据。当用户添加数据组件2时,它将作为道具转到组件1;当用户从组件1提交按钮时,两个组件数据存储在数据库中

当我在组件2中添加数据时,它将作为道具进入组件1,但出现错误。

组件1:

class SingleEmail extends Component {
    state = {
      data:this.props.content
    }

    onEditorChange=(evt) =>{
        this.setState({
          data: evt.editor.getData(),
        });
      }


      handleChange = (changeEvent)=> {
        this.setState({
          data: changeEvent.target.value,
        });
      }
      ondata = (value)=>{
        console.log("value",value)
      }

      onSubmit = (e) => {
        e.preventDefault();
        this.setState({
          data: this.state.data,
        })
        console.log("submit",this.state.data)
      }

    render() { 
     const EmailUser = (
      <div className="addresses">
        <div className="form-group row">
          <div className="col-sm-12">
          <CKEditor
        type="inline"
        data={this.state.data}
        onChange={this.onEditorChange}
      />
          </div>
        </div>

      </div>
    )
      return(<div className="container"><div className="col-md-12">
    {EmailUser}
      <Multifilefiledemail ondata={(value)=>this.ondata(value)}/>
      <button onClick={this.onSubmit} className="update-btn btn-info" type="button">Update Email</button>
    </div></div>)
    }
  }


  export default SingleEmail


Component 2 :

class Multifilefiledemail extends React.Component {
  state = {
    itemlist: [
      { label: "Two", id: "2", enabled: true },
      { label: "Three", id: "3", enabled: true },
      { label: "Four", id: "4", enabled: true }
    ],
    itemlist2: [],
    itemsToBeRemovedFromList1: [],
    itemsToBeRemovedFromList2: []
  };

  onChangeItemList1 = e => {
    const { itemlist, itemsToBeRemovedFromList1 } = this.state;
    const foundItem = itemlist.find(item => item.label == e.target.value);

    let allItems = [...itemsToBeRemovedFromList1, foundItem];

    //add item to the to be removed list
    this.setState({
      itemsToBeRemovedFromList1: [...allItems]
    });
    console.log("itemsToBeRemovedFromList1",this.state.itemsToBeRemovedFromList1)
  };

  onChangeItemList2 = e => {
    const { itemlist2, itemsToBeRemovedFromList2 } = this.state;
    const foundItem = itemlist2.find(item => item.label == e.target.value);

    //check for duplicates
    let allItems = [...itemsToBeRemovedFromList2, foundItem];

    //add item to the to be removed list
    this.setState({
      itemsToBeRemovedFromList2: [...allItems]
    });

  };

  handleadd = () => {
    const { itemlist, itemsToBeRemovedFromList1, itemlist2 } = this.state;
    const idsOfToBeRemovedItems = itemsToBeRemovedFromList1.map(
      item => item.id
    );
    const newItemList1 = itemlist.filter(
      item => !idsOfToBeRemovedItems.includes(item.id)
    );

    const newItemList2 = itemlist.filter(item =>
      idsOfToBeRemovedItems.includes(item.id)
    );

    this.setState({
      ...this.state,
      itemlist: newItemList1,
      itemlist2: [...itemlist2, ...newItemList2],
      itemsToBeRemovedFromList1: []
    },()=>this.props.ondata(this.state.itemlist2));
    console.log("send to database",this.state.itemlist2)

  };

  handleremove = () => {
    const { itemlist, itemsToBeRemovedFromList2, itemlist2 } = this.state;
    const idsOfToBeRemovedItems = itemsToBeRemovedFromList2.map(
      item => item.id
    );
    const newItemList2 = itemlist2.filter(
      item => !idsOfToBeRemovedItems.includes(item.id)
    );

    const newItemList1 = itemlist2.filter(item =>
      idsOfToBeRemovedItems.includes(item.id)
    );

    this.setState({
      ...this.state,
      itemlist: [...itemlist, ...newItemList1],
      itemlist2: newItemList2,
      itemsToBeRemovedFromList2: []
    });
  };

  render() {
    const { itemlist, itemlist2 } = this.state;

    return (
          <div className={`col-sm-12 bg-white alert`} style={modal.boxStyle}>
             <div className="addnewfield">

      <label> #3 Author Affiliation Countries   </label>

    <div className="row">
    <div className="col-md-5">      
      <select
          className="custom-select"
          onChange={this.onChangeItemList1}
          multiple
        >
          {itemlist &&
            itemlist.map(item => (
              <option id={item.id} value={item.label}>
                {item.label}
              </option>
            ))}
        </select>

    </div>
    <div className="col-md-2 ">      
    <button onClick={this.handleadd} class="btn btn-primary btn-block w-25 margin-bottom">
      <i class="fa fa-arrow-right"></i>
    </button>
    <button onClick={this.handleremove}class="btn btn-primary btn-block w-25">
      <i class="fa fa-arrow-left"></i>
    </button>
    </div>
    <div className="col-md-5">      
    <select
          className="custom-select"
          onChange={this.onChangeItemList2}
          multiple
        >
          {itemlist2 &&
            itemlist2.map(item => (
              <option id={item.id} value={item.label}>
                {item.label}
              </option>
            ))}
        </select>

    </div>
  </div>
             </div>

           <button
            type="button"
            onClick={ ()=>this.props.history.push('/email/edit-email/' + 3 )}
            data-toggle="modal"
            data-target="#exampleModal"
            className="btn btn-info waves-effect waves-light"
            >Configure email</button>
        </div> : ''
    )
  }
}



export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Multifilefiledemail));

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

请勿使用此类道具。最好让道具自己动手。

state = {
     data:this.props.content
}

如果您被迫将道具置于某种状态,请检查此文档。

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops