React Pass function to child component

前端 未结 4 1931
轮回少年
轮回少年 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:19

    If you can bind this function like this it will works

    class Parent extends Component {
       passedFunction = () => {};
       render() {
       <Child passedFunction={this.passedFunction} />;
      }
    }
    
    class Child extends Component {
       render() {
       <div onClick={this.props.passedFunction} />;
      }
    }
    
    0 讨论(0)
  • 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() {
            <div onClick={this.props.passedFunction}></div>
        }
    }
    
    class Parent extends Component {
        passedFunction = () => {}
        render() {
          <Child passedFunction={this.passedFunction}/>
        }
    }
    

    To Account for older version support of Javascript:

    class Child extends Component {
        render() {
            <div onClick={this.props.passedFunction}></div>
        }
    }
    
    class Parent extends Component {
        constructor() {
            this.passedFunction = this.passedFunction.bind(this)
        }
    
        passedFunction() {}
        render() {
          <Child passedFunction={this.passedFunction}/>
        }
    }
    
    0 讨论(0)
  • 2020-12-05 12:36

    You are missing bind on the Child component.

    this.props.passedFunction.bind(this)
    
    0 讨论(0)
  • 2020-12-05 12:38

    I found out what was wrong. It was because of react-grid-layout. I have to pass the rest of the properties to child.

    class Child extends Component {
        render() {
            var { passedFunction, ...otherProps } = this.props;
            return (
                <div onClick={passedFunction} {...otherProps}></div>
            );           
        }
    }
    
    0 讨论(0)
提交回复
热议问题