React Pass function to child component

前端 未结 4 1934
轮回少年
轮回少年 2020-12-05 11:38

I want to pass a function to a child component but I\'m getting this error.

Invalid value for prop passedFunction on

tag.

c         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 12:30

    Instead of having to bind your function in the constructor of the parent Class, you can use an arrow function to define your method so it is lexically bound using an arrow function

    class Child extends Component {
        render() {
            
    } } class Parent extends Component { passedFunction = () => {} render() { } }

    To Account for older version support of Javascript:

    class Child extends Component {
        render() {
            
    } } class Parent extends Component { constructor() { this.passedFunction = this.passedFunction.bind(this) } passedFunction() {} render() { } }

提交回复
热议问题