Lun*_*ang 4 reactjs react-grid-layout
我想将一个函数传递给子组件,但出现此错误。
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>
}
}
Run Code Online (Sandbox Code Playgroud)
基本上是我想做的。
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>
)
}
});
Run Code Online (Sandbox Code Playgroud)
似乎它是在React v16中引入的。因此,将函数从父代传递给子代的正确方法是什么?
不必在父类的构造函数中绑定函数,您可以使用箭头函数定义您的方法,以便使用箭头函数按词法绑定
class Child extends Component {
render() {
<div onClick={this.props.passedFunction}></div>
}
}
class Parent extends Component {
passedFunction = () => {}
render() {
<Child passedFunction={this.passedFunction}/>
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
您缺少 Child 组件上的绑定。
this.props.passedFunction.bind(this)
Run Code Online (Sandbox Code Playgroud)
我发现出了什么问题。这是因为react-grid-layout。我必须将其余的财产传递给孩子。
class Child extends Component {
render() {
var { passedFunction, ...otherProps } = this.props;
return (
<div onClick={passedFunction} {...otherProps}></div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28636 次 |
| 最近记录: |