javascript - 如何通过 onclick 子组件将数据传递给父组件 react

标签 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>

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

最佳答案

假设这是您的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>
       )
    }
}

关于javascript - 如何通过 onclick 子组件将数据传递给父组件 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56933758/

相关文章:

reactjs - React hooks 相当于 componentDidCatch?

javascript - 打开新窗口

javascript - 动态添加点击事件到复选框,仅适用于第一个复选框JQUERY

javascript - 正则表达式 - 无效表达式错误 "Nothing to repeat at..."

node.js - Docker 容器 'Connect ECONNREFUSED localhost'

javascript - ES6 使用构造函数参数设置此属性

css - Flexbox 布局上从绝对元素到固定元素

php - PHP + JS的模板引擎但是

node.js - Mongoose 对象文字子文档不可访问

javascript - 在 React JS 中使用 Jest 修复单元测试错误