React Pass function to child component

非 Y 不嫁゛ 提交于 2019-12-06 05:10:51

问题


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

Invalid value for prop passedFunction on <div> tag.

class Parent extends Component {
    passedFunction(){}
    render() {
      <Child passedFunction={this.passedFunction}/>
    }
}

class Child extends Component {
    render() {
        <div onClick={this.props.passedFunction}></div>
    }
}

Basically what I'm trying to do.

var ReactGridLayout = require('react-grid-layout');

var MyFirstGrid = React.createClass({
passedFunction:function(){}
  render: function () {
    return (
      <ReactGridLayout className="layout" cols={12} rowHeight={30} width={1200}>
        <div key="a" data-grid={{x: 0, y: 0, w: 1, h: 2, static: true}}>a</div>
        <div key="b" data-grid={{x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4}}>b</div>
        <div key="c" data-grid={{x: 4, y: 0, w: 1, h: 2}} passedFunction={this.passedFunction}>c</div>
      </ReactGridLayout>
    )
  }
});

It seems it was introduced in React v16. Therefore, what is the correct way to pass a function from parent to child?


回答1:


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}/>
    }
}



回答2:


You are missing bind on the Child component.

this.props.passedFunction.bind(this)



回答3:


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>
        );           
    }
}



回答4:


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} />;
  }
}


来源:https://stackoverflow.com/questions/48407785/react-pass-function-to-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!