反应传递函数到子组件 [英] React Pass function to child component

查看:52
本文介绍了反应传递函数到子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将函数传递给子组件,但出现此错误.

上的 proppassedFunction 的值无效标签.

class Parent extends Component {传递函数(){}使成为() {<Child passedFunction={this.passedFunction}/>}}类子扩展组件{使成为() {<div onClick={this.props.passedFunction}></div>}}

基本上就是我想要做的.

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

var MyFirstGrid = React.createClass({通过函数:函数(){}渲染:函数(){返回 (<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>)}});

它似乎是在 React v16 中引入的.因此,将函数从父级传递给子级的正确方法是什么?

解决方案

我发现了问题所在.这是因为反应网格布局.我必须将其余的属性传递给孩子.

class Child extends Component {使成为() {var { passFunction, ...otherProps } = this.props;返回 (<div onClick={passedFunction} {...otherProps}></div>);}}

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?

解决方案

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

这篇关于反应传递函数到子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆