React - change input defaultValue by passing props

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

Consider this example:

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

        
7条回答
  •  情歌与酒
    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:

    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.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.

提交回复
热议问题