Using an input field with onBlur and a value from state blocks input in Reactjs JSX?

放肆的年华 提交于 2019-12-09 02:51:23

问题


I've made a small fiddle to show the problem: http://jsfiddle.net/4TpnG/582/ When you have an input box with onBlur attached to it, and an initial value from state, input from the keyboard is blocked. When onChange is attached, it's working correctly. Why is this happening and how can this be solved? I would have expected it to accept the characters you type and update the state onBlur.

var Test = React.createClass({

      getInitialState: function() {
        return {
          value: "hallo"
        };
      },

      render: function() {
          return ( < form >
            < div >
            Onchange: < input type = "text"
            value = {
              this.state.value
            }
            onChange = {
              this.handleChange
            }
            /><br/ >
            Onblur: < input type = "text"
            value = {
              this.state.value
            }
            onBlur = {
              this.handleChange
            }
            />
      </div >
            < /form>
    );
  },
  handleChange: function(e){
      this.setState({value: e.target.value});
  }
});

React.renderComponent(<Test/ > , document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/react-with-addons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/JSXTransformer.js"></script>

回答1:


The value attribute ties the value of the input to that state, and if the user changes the value then the state and the input value is no longer tied to each other. So React stops that from happening.

You probably want to use the defaultValue attribute instead.

If you want to use the value attribute you need the onChange to sync it with the component state. This because the component can re-render at any time, and if the value is out of sync with the state that would render an old value.



来源:https://stackoverflow.com/questions/30345822/using-an-input-field-with-onblur-and-a-value-from-state-blocks-input-in-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!