javascript - 如何在 React 中的子组件和父组件之间共享数据?
问题描述
我的反应应用程序中有两个组件(表格组件和用户组件)。我的一个组件的表中有多个用户数据。单击按钮时,我需要将用户 ID 从 Table 组件传递给 User 组件。问题是当我从表组件调用该属性时,它this.props.onClick is not a function
在控制台中出现错误。我该如何解决这个问题?
表格组件:
class EnhancedTable extends React.Component {
constructor(props){
super(props);
this.state = {
userID: 10
};
this.sendUserId = this.sendUserId.bind(this);
}
sendUserId() {
this.props.onClick(this.state.userID);
}
render() {
return (
<button onClick={this.sendUserId}>
<BorderColorIcon className="action margin-r" />
</button>
)
}
}
用户组件:
Import EnhancedTable from './EnhancedTable';
class Users extends Component {
constructor(props) {
super(props);
this.state = {
userID: 5
};
this.onFillForm = this.onFillForm.bind(this);
}
onFillForm(idd) {
this.setState({
userID : idd
})
}
render() {
return(
<span onClick = {this.onFillForm} className="mainUserDivTitle">{this.state.userID}</span>
)
}
}
解决方案
假设:EnhancedTable 是子组件,User 是父组件。
您的代码有问题:您没有调用 Child 组件,因此 EnhancedTable 没有得到this.props.onClick
.
你需要像这样调用EnhancedTable:
<EnhancedTable onClick = {this.onFillForm} />