reactjs在两个组件之间传输数据

时间:2017-05-31 08:19:52

标签: reactjs

在反应中我有2个组件。

在Component1.jsx中:

import Info from Component2.jsx; 
... 
...
var dataInfo = "some info.. ";
<Info dataInfo={dataInfo} />
...
... 

在上面的代码中,我们将表单中的数据从component1.jsx转移到component2.jsx

以同样的方式,我们可以将数据传输回component2.jsx到component1.jsx吗?

请帮帮我。我试图在谷歌找到答案,但无法正常。

1 个答案:

答案 0 :(得分:1)

是的,您可以转回父母组件, 我将举例说明你如何做到这一点

假设您有一个父母,它被称为component1,并且它有一个作为子项导入的表单,名为component2

如下:

import React, { Component } from 'react';
export default class Component2 extends Component{

constructor() {
    super();

    this.state = {
        UserName: '',
        email: ''
    };
    this.onSubmit = this.onSubmit.bind(this)
}

onSubmit(e){
    e.preventDefault();
    var field = {
        UserName:  this.state.UserName,
        email :   this.state.email,
        password:  this.state.password,
    }
    **this.props.onUpdate(field);**
}
onChange(e){
    this.setState({
        [e.target.name]: e.target.value
    });
}
render() {
    var UserNameError = **this.props.UserNameError**;
    var emailError = **this.props.emailError**;

    return(

        <div className="col-md-6 col-sm-6">
            <div className="title">Create Account</div>
            <Form onSubmit={this.onSubmit}>
                <div className="form-group">
                    <label>user Name</label>
                    <input onChange={this.onChange.bind(this)} value={this.state.UserName} name='UserName'/>
                    <span className="error is-visible">{UserNameError}</span>
                </div>
                <div className="form-group">
                    <label>Email</label>
                    <input onChange={this.onChange.bind(this)} value={this.state.email} name='email' />
                    <span className="error is-visible">{emailError}</span>
                </div>

                <Button className='btn submit'>Register</Button>
            </Form>
        </div>
    )
}}
import React, { Component } from 'react';
import Component2 from './Component2'
export default class Component1 extends Component{
    constructor() {
        super();
        this.state = {
            UserName: '',
            email: '',
            UserNameError:' UserNameError ',
            emailError:' emailError '
        };
    }
    onUpdate(val) {
        this.setState({
            email: val.email,
            UserName: val.UserName,
        });
        console.log(' onSubmit  ** email' + val.email + " UserName " + val.UserName )
    };
    render() {
        return(
            <div className="col-md-6 col-sm-6">
                <Component2 **UserNameError={this.state.UserNameError}** **emailError={this.state.emailError}** **onUpdate={this.onUpdate.bind(this)}**  />
            </div>
        )

    }
}

我把星号放在句子周围,注意我如何将数据错误从父Component1传输到component2

以及如何通过onUpdate函数从子Component2发送Form数据到Component1