我如何通过onclick冷组件将数据传递给父组件做出反应

时间:2019-07-08 11:16:30

标签: javascript node.js reactjs

如何通过使用onclick事件将数据从子组件传递到父组件。

我通常在我的应用程序中使用此代码。每当我单击按钮时,我都会在父组件CreateEmail中看到它称为函数:

ƒ (selectedItem) {
        var listofdata = _this.state.listofdata;
    }

     dddd = (selectedItem) => {
        const { listofdata } = this.state;

        const newList = [...listofdata];


        const itemIndex = newList.findIndex(item => item.name === selectedItem.name);

        if (itemIndex > -1) {
          newList.splice(itemIndex, 1);
        } else {
          newList.push(selectedItem);
        }

        this.setState({
          listofdata: newList
        })

      }

    <CreateEmail dddd={this.dddd}/>

       <button onClick={() => this.dddd(item)} className=" btn btn-info waves-effect waves-light" >+</button>

当我单击按钮时,我只需要获取数据。

1 个答案:

答案 0 :(得分:1)

假设这是您的parent.js

class parent extends React.Component{

  dddd = (selectedItem) => {
        const { listofdata } = this.state;

        const newList = [...listofdata];


        const itemIndex = newList.findIndex(item => item.name === selectedItem.name);

        if (itemIndex > -1) {
          newList.splice(itemIndex, 1);
        } else {
          newList.push(selectedItem);
        }

        this.setState({
          listofdata: newList
        })

      }
render(){
  return(
     <CreateEmail dddd={this.dddd}/> //child component added
  )
}
}

这是您的子组件CreateEmail.js

class CreateEmail extends React.Component{
    constructor(props){
      super(props);
      this.state = {
        item: '';
      }
    }
    handleClick = () =>{
         //here you should have logic to get data which you want to pass to parent component either maintain in state
        this.props.dddd(this.state.item)
    }
    render(){
       return(
           <button onClick={() => this.handleClick} className=" btn btn-info waves-effect waves-light" >+</button>
       )
    }
}