我的react应用程序中有两个组件(“父组件”和“子组件”)。我的子组件中有两次单击按钮,我需要将两个道具传递给父组件。我使用如下代码。 问题是,我不能在父组件的元素中同时包含这两种方法,但我需要这样做。如何在父组件中同时使用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;}}/>
)
}
}
答案 0 :(得分:5)
您错过了()
<EnhancedTable onClick = {(e)=>{this.editUser(); this.deleteUser();}}/>
答案 1 :(得分:4)
您正在
<EnhancedTable onClick = {(e)=>{this.editUser; this.deleteUser;}}/>
需要稍作更改:
<EnhancedTable onClick = {(e)=>{this.editUser(e); this.deleteUser(e);}}/>
这里有什么变化的快速参考:
let x = () => {
console.log('hello');
}
x; // This simply does nothing as it is just a reference to the function
x(); // This instead invokes the function