首页 > 解决方案 > 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在这里不被识别为功能?

标签: javascriptreactjs

解决方案


请检查这个例子,我只发现不同之处<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>
        );
    }
}

推荐阅读