javascript - React 父子通信:TypeError: _this.state.myFunction is not a function
问题描述
我是 React 世界的新手,我正在尝试使用应该从子组件调用的函数来构建父组件。但是,当我调用该函数时,我在标题中收到错误消息。我有类似的东西:
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.myFunction = this.myFunction.bind(this);
}
myFunction(param) {
//do something
}
render(){
return(
<ChildComponent event={this.myFunction} />
);
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
inheritedFunction: this.props.event
};
}
childFunction(param) {
//do a few things first
this.state.inheritedFunction(param);
}
render(){
return(
<input type="checkbox" onChange={this.childFunction.bind(this)></input>
);
}
}
我的代码编译并运行,然后当它在选中复选框时执行 childFunction() 时,this.state.inheritedFunction(param) 说它不是一个函数并且应用程序崩溃了。我怀疑它必须与绑定有关,但我真的不确定并坚持这个问题。
我是 React 的新手,所以请善待。:-) 有人知道我搞砸了什么吗?
解决方案
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.myFunction = this.myFunction.bind(this);
}
myFunction = (param) => {
//do something
alert(param);
}
render(){
return(
<ChildComponent event={this.myFunction} />
);
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
inheritedFunction: this.props.event
};
}
childFunction(param) {
//do a few things first
this.props.event(param);
}
render(){
return(
<input type="checkbox" onChange={this.childFunction.bind(this)></input>
);
}
}
推荐阅读
- javascript - Vue如何将元素添加到v-for循环
- sql - SQL JSON 帮助 | 选择具有特定 JSON 值的所有记录
- grpc - 具有相同代码的主机之间的 gRPC HTTP/2 设置不同——它们在哪里设置?
- javascript - 从复选框中删除是勾选
- python - 尝试在 Dockerfile 中安装 Comet ML 3.18 时出现 glibc 的 Conda UnsatisfiableError
- tensorflow - 如何修改镜像策略/分布式训练的分类交叉熵?
- amazon-web-services - 有没有办法缩短在 AWS IoT 中触发生命周期事件的时间?
- ios - Swift & Navigation:如何替换 ViewController 并发送一些参数?
- arrays - a[0] 指向哪里?
- python - 如何使用文件处理添加创建一个 txt 文件,该文件将玩家的分数保存在 python 上的简单猜数字游戏中?