React form onChange->setState one step behind

前端 未结 7 1570
南方客
南方客 2020-12-02 12:21

I encountered this problem building a webapp and I replicated it in this jsfiddle. Essentially, I would like an input to call this.setState({message: input_val})

7条回答
  •  感情败类
    2020-12-02 12:41

    There's no reason for MyForm to be using state here. Also putting the onChange on the form instead of the input you're interested in is odd. Controlled components should be preferred because their behavior is more obvious, and any time App's message state changes (even if you e.g. allow Message to change it later), it'll be correct everywhere.

    This also makes your code a bit shorter, and considerably simpler.

    var App = React.createClass({
        getInitialState: function() {
            return {message: ''}
        },
        appHandleSubmit: function(message) {
            this.setState({message: message});
        },
        render: function() {
            return (
                
    ); } }); var MyForm = React.createClass({ handleInputChange: function(e){ this.props.onChange(e.target.value); }, // now always in sync with the parent's state render: function() { return (
    ); } });

    jsbin

提交回复
热议问题