React - 通过传递props更改输入defaultValue [英] React - change input defaultValue by passing props

查看:446
本文介绍了React - 通过传递props更改输入defaultValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个例子:

  var Field = React.createClass({
render:function(){
//永远不会呈现新值...
return(
< div>
< input type =textdefaultValue = {this.props.value ||''' } />
< / div>
);
}
});

var App = React.createClass({
getInitialState:function(){
return {value:'Hello!'};
},

changeTo:function(str){
this.setState({value:str});
},

render:function(){
返回(
< div>
<字段值= {this.state.value} />
<按钮onClick = {this.changeTo.bind(null,'Whyyyy? ')}>更改为Whyyyy?< / button>
< button onClick = {this.changeTo.bind(null,void 0)}>更改为undefined< / button>
< / div>
);
}
});

React.render(
< App />,
document.getElementById('app')
);

我想将值传递给 defaultValue as愚蠢的输入组件的支柱。但它永远不会重新呈现它。

解决方案

如上所述, defaultValue 仅在表单的初始加载时设置。之后,它不会自然更新,因为意图只是设置一个初始默认值。



如果需要通过,你可以绕过这个包装器组件的,例如字段 App 组件,但在更实际的情况下,它可能是一个表单组件。一个好的将是传递给表单的资源的唯一值 - 例如,存储在数据库中的id。



在简化的情况下,您可以在Field渲染中执行此操作:

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

在更复杂的表格情况下,这样的东西可能会得到你想要的东西,例如你的onSubmit提交给API的操作但保留在同一页面上:

  const Form =({item,onSubmit})=> {
return(
< form onSubmit = {onSubmit} key = {item.id}>
< label>
名字
<输入类型=textname =firstNamedefaultValue = {item.firstName} />
< / label>
< label>
姓氏
<输入类型=textname =lastNamedefaultValue = {item.lastName} />
< / label>
< button>提交!< / button>
< / form>

}

Form.defaultProps = {
item:{}
}

Form.propTypes = {
item:PropTypes.object,
onSubmit:PropTypes.func.isRequired
}

当使用不受控制的表单输入时,我们通常不会关心这些值,直到它们被提交之后,这就是为什么在你真正想要更新defaultValues时强制重新渲染的更理想的原因(之后)提交,而不是对每个输入的每次更改)。



如果您还在编辑相同的表单并担心API响应可能会返回不同的值,您可以提供id加时间戳等组合键。 / p>

Consider this example:

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

var App = React.createClass({
    getInitialState: function () {
        return {value: 'Hello!'};
    },

    changeTo: function (str) {
        this.setState({value: str});
    },

    render: function () {
        return (
            <div>
                <Field value={this.state.value} />
                <button onClick={this.changeTo.bind(null, 'Whyyyy?')}>Change to "Whyyyy?"</button>
                <button onClick={this.changeTo.bind(null, void 0)}>Change to undefined</button>
            </div>
        );
    }
});

React.render(
    <App />,
    document.getElementById('app')
);

I want to pass value into defaultValue as prop of dumb input component. However it never re-renders it.

解决方案

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.

这篇关于React - 通过传递props更改输入defaultValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆