javascript - ReactJS:将函数传递给子组件会导致 TypeError
问题描述
我正在尝试从 parent->child 传递一个回调函数,但是当渲染子组件时,我收到错误:TypeError: this.props.setCurrentWindow is not a function
.
我试图传递函数的父组件setCurrentWindow
class Parent extends Component {
constructor(props){
super(props);
this.setCurrentWindow = this.setCurrentWindow.bind(this);
}
setCurrentWindow(){
console.log("called")
}
render(){
return(
<Child
setCurrentWindow={this.setCurrentWindow}
/>)}
}
我试图调用的子组件setCurrentWindow
class Child extends Component{
constructor(props){
super(props)
}
render(){
return(
<div
onClick={()=>{this.props.setCurrentWindow()}}>
{this.props.children}
</div>
)}
}
为什么setCurrentWindow
在这里不被识别为功能?
解决方案
请检查这个例子,我只发现不同之处<div><h1>Hello</h1></div>
在于你的代码中没有这样的子元素。除此之外,一切正常。当我单击 div 时,它会写入call inconsole
export default class Parent extends Component {
constructor(props) {
super(props);
this.setCurrentWindow = this.setCurrentWindow.bind(this);
}
setCurrentWindow() {
console.log("called")
}
render() {
return (
<Child
setCurrentWindow={this.setCurrentWindow}
>
<div>
<h1>Hello</h1>
</div>
</Child>
)
}
}
class Child extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div onClick={() => {
this.props.setCurrentWindow()
}}>
{this.props.children}
</div>
);
}
}
推荐阅读
- typescript - 如何在打字稿中根据类类型调用方法?
- android - 如何构建应用程序来注册指纹以进行身份验证
- python - 如何在python中腌制外部仪器状态
- css - 自定义元素的命名问题
- joomla - Joomla 的 GTranslate 显示 400 错误并停止工作
- python - 当我尝试使用命令行参数清除数据库时,db.drop_all() 没有给出这样的表错误
- go - 如何从 filepath.walkDir() 中排除根目录?
- python - 如何设计具有两个分量的联合损失函数,以最小化第一个损失但最大化第二个损失?
- node.js - msg.author.dmChannel 不存在
- python - 提取信息