ReactJS调用父方法 [英] ReactJS call parent method

查看:125
本文介绍了ReactJS调用父方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ReactJS中迈出了第一步,并尝试了解父母和孩子之间的沟通。
我正在制作表格,所以我有造型领域的组件。此外,我还有包含字段并检查它的父组件。示例:

I'm making my first step in ReactJS and trying to understand communication between parent and children. I'm making form, so I have the component for styling fields. And also I have parent component that includes field and checking it. Example:

var LoginField = React.createClass({
    render: function() {
        return (
            <MyField icon="user_icon" placeholder="Nickname" />
        );
    },
    check: function () {
        console.log ("aakmslkanslkc");
    }
})

var MyField = React.createClass({
    render: function() {
...
    },
    handleChange: function(event) {
//call parent!
    }
})

有没有办法做到这一点。我的逻辑在反应世界中是好的吗?感谢您的时间。

Is there any way to do it. And is my logic is good in reactjs "world"? Thanks for your time.

推荐答案

为此,您将回调作为属性传递给父级的子级。

To do this you pass a callback as a property down to the child from the parent.

例如:

var Parent = React.createClass({

    getInitialState: function() {
        return {
            value: 'foo'
        }
    },

    changeHandler: function(value) {
        this.setState({
            value: value
        });
    },

    render: function() {
        return (
            <div>
                <Child value={this.state.value} onChange={this.changeHandler} />
                <span>{this.state.value}</span>
            </div>
        );
    }
});

var Child = React.createClass({
    propTypes: {
        value:      React.PropTypes.string,
        onChange:   React.PropTypes.func
    },
    getDefaultProps: function() {
        return {
            value: ''
        };
    },
    changeHandler: function(e) {
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(e.target.value);
        }
    },
    render: function() {
        return (
            <input type="text" value={this.props.value} onChange={this.changeHandler} />
        );
    }
});

在上面的示例中, Parent 调用,属性为 value onChange 。返回的 Child onChange 处理程序绑定到标准< input /> 元素并将值传递给 Parent 的回调(如果已定义)。

In the above example, Parent calls Child with a property of value and onChange. The Child in return binds an onChange handler to a standard <input /> element and passes the value up to the Parent's callback if it's defined.

因此,调用 Parent changeHandler 方法,第一个参数是<$ c中的字符串值子中的$ c>< input /> 字段。结果是 Parent 的状态可以使用该值更新,从而导致父级的< span /> Child 的输入字段中键入时使用新值更新的元素。

As a result the Parent's changeHandler method is called with the first argument being the string value from the <input /> field in the Child. The result is that the Parent's state can be updated with that value, causing the parent's <span /> element to update with the new value as you type it in the Child's input field.

这篇关于ReactJS调用父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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