React在表单提交上获取输入值并显示它

时间:2017-01-01 11:56:25

标签: javascript reactjs

我有以下脚本:http://codepen.io/AlexanderWeb00/pen/gLVbjL?editors=0010

class Wrapper extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ''
    };
  }
  handleFirstName(e) {
    this.setState({name: e.target.value});
  }
  render(){
    return (
      <section>
        <h2>welcome</h2>
        <TShirt name={this.state.name} />
        <FormButton action={this.handleFirstName.bind(this)} />
      </section>
    )
  }
};

class TShirt extends React.Component {
  render(){
    return (
      <section>
        <div>
          <p>Name: {this.props.name}</p>
        </div>
      </section>
    )
  }
};
class Extention extends React.Component {
  render(){
    return (
      <section>
        <div>
          <p>badaboom</p>
        </div>
      </section>
    )
  }
};
var FormButton = React.createClass({ 
    getInitialState: function() {
        return {'submitted': false};
    },

    handleSubmit: function(e) {
        e.preventDefault();
        this.setState({'submitted': true });
    },
    render: function() {
        if (this.state.submitted) {
            return <Extention/>;
        }
        else {
            return (
                <form role="form" onSubmit={this.handleSubmit}>
                    <input type="text" />
                    <input type="submit" value="submit" />
                </form> 
            );
        }
    }
}); 

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

我想显示从输入中收集的值

<input type="text" />

这里:

<p>Name: {this.props.name}</p>, inside the TShirt component.

目前只提交表单后才显示新组件。在构建应用程序时,Tshirt组件将更新更多内容。

1 个答案:

答案 0 :(得分:1)

您可以使用refs获取tshirt输入字段的值,然后调用传递给action prop中的FormButton组件的回调函数。

var FormButton = React.createClass({ 
getInitialState: function() {
    return {'submitted': false};
},

handleSubmit: function(e) {
    e.preventDefault();
    var tshirt = this.refs.tshirt.value;
    this.setState({submitted: true }, function() {
      this.props.action(tshirt);
    });
},
render: function() {
    if (this.state.submitted) {
        return <Extention/>;
    }
    else {
        return (
            <form role="form" onSubmit={this.handleSubmit}>
                <input type="text" ref="tshirt" />
                <input type="submit" value="submit" />
            </form> 
        );
    }
}
});

然后将 handleFirstName 方法修改为:

handleFirstName(tshirt) {
    this.setState({name: tshirt});
}