React - change input defaultValue by passing props

后端 未结 7 1955
星月不相逢
星月不相逢 2020-12-24 13:02

Consider this example:

var Field = React.createClass({
    render: function () {
        // never renders new value...
        return (
            

        
相关标签:
7条回答
  • 2020-12-24 13:34

    I'm fairly certain this has to do with Controlled vs. Uncontrolled inputs.

    If I understand correctly, since your <input> is Uncontrolled (doesn't define a value attribute), then the value will always resolve to the value that it is initialized with. In this case Hello!.

    In order to overcome this issue, you can add a value attribute and set it during the onChange:

    var Field = React.createClass({
          render: function () {
              // never renders new value...
              return (
                  <div>
                      <input type="text" defaultValue={this.props.default || ''} value={this.props.value} />
                  </div>
              );
          }
      });
    

    Here is a plunker showing the change.

    0 讨论(0)
  • 2020-12-24 13:41

    defaultValue only works for the initial load. After that, it won't get updated. You need to maintain the state for you Field component:

    var Field = React.createClass({
        //transfer props to state on load
        getInitialState: function () {
            return {value: this.props.value};
        },
        //if the parent component updates the prop, force re-render
        componentWillReceiveProps: function(nextProps) {
             this.setState({value: nextProps.value});
        },
        //re-render when input changes
        _handleChange: function (e){
            this.setState({value: e.target.value});
        },
        render: function () {
            // render based on state
            return (
                <div>
                    <input type="text" onChange={this._handleChange} 
                                       value={this.state.value || ''} />
                </div>
            );
        }
    });
    
    0 讨论(0)
  • 2020-12-24 13:44

    You can make the input conditionally and then every time you want to force an update of the defaultValue you just need to unmount the input and then immediately render it again.

    0 讨论(0)
  • 2020-12-24 13:48

    I also face this problem, what I did was to manually update the input value when the props has change. Add this to your Field react class:

    componentWillReceiveProps(nextProps){
        if(nextProps.value != this.props.value) {
            document.getElementById(<element_id>).value = nextProps.value
        }
    }
    

    You just need to add an id attribute to your element so that it can be located.

    0 讨论(0)
  • 2020-12-24 13:50

    As a previous answer mentioned, defaultValue only gets set on initial load for a form. After that, it won't get "naturally" updated because the intent was only to set an initial default value.

    You can get around this if you need to by passing a key to the wrapper component, like on your Field or App component, though in more practical circumstances, it would probably be a form component. A good key would be a unique value for the resource being passed to the form - like the id stored in the database, for example.

    In your simplified case, you could do this in your Field render:

    <div key={this.props.value}>
        <input type="text" defaultValue={this.props.value || ''} />
    </div>
    

    In a more complex form case, something like this might get what you want if for example, your onSubmit action submitted to an API but stayed on the same page:

    const Form = ({item, onSubmit}) => {
      return (
        <form onSubmit={onSubmit} key={item.id}>
          <label>
            First Name
            <input type="text" name="firstName" defaultValue={item.firstName} />
          </label>
          <label>
            Last Name
            <input type="text" name="lastName" defaultValue={item.lastName} />
          </label>
          <button>Submit!</button>
        </form>
      )
    }
    
    Form.defaultProps = {
      item: {}
    }
    
    Form.propTypes = {
      item: PropTypes.object,
      onSubmit: PropTypes.func.isRequired
    }
    

    When using uncontrolled form inputs, we generally don't care about the values until after they are submitted, so that's why it's more ideal to only force a re-render when you really want to update the defaultValues (after submit, not on every change of the individual input).

    If you're also editing the same form and fear the API response could come back with different values, you could provide a combined key of something like id plus timestamp.

    0 讨论(0)
  • 2020-12-24 13:56

    The issue is here:

    onClick={this.changeTo.bind(null, 'Whyyyy?')}
    

    I'm curious why you bind to null.

    You want to bind to 'this', so that changeTo will setState in THIS object.

    Try this

    <button onClick={this.changeTo.bind(this, 'Whyyyy?')}>Change to "Whyyyy?"</button>
    <button onClick={this.changeTo.bind(this, void 0)}>Change to undefined</button>
    

    In Javascript, when a function is called, its called in the scope where it was called from, not where it was written (I know, seems counter intuitive). To ensure it is called in the context you write it, you need to '.bind(this)'.

    To learn more about binding and function scope, there are lots of online tutes, (some much better than others) - you might like this one: http://ryanmorr.com/understanding-scope-and-context-in-javascript/

    I also recommend using the React Dev tools if you are using firefox or chrome, this way you would have been able to see that state.message was not changing: https://facebook.github.io/react/blog/2015/09/02/new-react-developer-tools.html

    0 讨论(0)
提交回复
热议问题