Javascript 在更改方法上使用输入子控件反应控件父状态

Javascript 在更改方法上使用输入子控件反应控件父状态,javascript,reactjs,Javascript,Reactjs,我有以下资料: import React from 'react'; import {render} from 'react-dom'; class TShirt extends React.Component { render () { return <div className="tshirt">{this.props.name}</div>; } } class FirstName extends React.Component

我有以下资料:

import React from 'react';
import {render} from 'react-dom';

class TShirt extends React.Component {
    render () {
        return <div className="tshirt">{this.props.name}</div>;
    }
}

class FirstName extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            submitted: false
        };
    }
    getName () {
        var name = this.refs.firstName.value;
        this.setState({ submitted: true }, function() {
          this.props.action(name);
        });
    }
    render () {
        return (
            <div>
                <h2>tell us your first name</h2>
                <form>
                    <input 
                        type="text"
                        ref="firstName"
                        onChange={this.getName.bind(this)}
                    />
                    <div className="buttons-wrapper">
                        <a href="#">back</a>
                        <button>continue</button>
                    </div>
                </form>
            </div>
        );
    }
}

class Nav extends React.Component {
    render () {
        return <p>navigation</p>;
    }
}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: ''
        };
    }
    getName (tshirt) {
        this.setState({ name:tshirt })
    }
    render () {
        return (
            <section>
                <Nav />
                <TShirt name={this.state.name} />
                <FirstName action={this.getName} />
            </section>
        );
    }
}

render(<App/>, document.getElementById('app'));

您必须将
getName
函数绑定到
this

在你的构造器里

this.getName = this.getName.bind(this);
然后,您的构造函数应该如下所示

constructor(props) {
    super(props);
    this.state = {
        name: ''
    };
    this.getName = this.getName.bind(this);
}

这是正确的,但您也可以使用ES6 fat arrow函数,该函数将自动绑定
This
,如
getName(tshirt)=>{…}
。可能重复
constructor(props) {
    super(props);
    this.state = {
        name: ''
    };
    this.getName = this.getName.bind(this);
}