首页 > 解决方案 > 如何在 onClick 中调用多个方法进行反应?

问题描述

我的反应应用程序中有两个组件(父组件和子组件)。我的子组件中有两个按钮单击,我需要将两个道具传递给父组件。我使用如下代码。问题是,我不能在父组件的元素中包含这两种方法,但我需要。如何在父组件中同时使用 edituser 和 deleteuser 函数?

子组件:

class EnhancedTable extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      userID: 10
    };
    this.editByUserId = this.sendUserId.bind(this);
    this.DeleteByUserId = this.sendUserId.bind(this);
  }

  editByUserId() {
    this.props.onClick(this.state.userID);
  }

  DeleteByUserId() {
    this.props.onClick(this.state.userID);
  }

  render() {
    return (
       <button onClick={this.sendUserId}>
           <BorderColorIcon onClick={this.editUserById} className="action margin-r" />
           <DeleteIcon onClick={this.deleteUserById} className="action margin-r" />
       </button>
    )
  }
}

父组件:

Import EnhancedTable from './EnhancedTable';

class Users extends Component {

  constructor(props) {
    super(props);
    this.state = {
      userID: null
    };
    this.editUser = this.editUser.bind(this);
    this.deleteUser = this.deleteUser.bind(this);
   }

  editUser(idd) {
    this.setState({
      userID : idd
    })
    console.log("User Edited");
  }

   deleteUser(idd) {
      this.setState({
        userID : idd
      })
      console.log("User Deleted");
    }

  render() {
     return(
         <EnhancedTable onClick = {(e)=>{this.editUser; this.deleteUser;}}/>
     )
   }
}

标签: javascriptreactjs

解决方案


你错过了你的 ()

<EnhancedTable onClick = {(e)=>{this.editUser(); this.deleteUser();}}/>

推荐阅读