我目前正在使用React构建一个表单,我想知道从对象中预填充字段的最佳实践是什么。
import React, { Component } from 'react'
class EditResourceForm extends Component {
constructor (props) {
super(props)
this.state = {
resource: props.resource
}
}
handleFieldChanged (e) {
// update state
}
render () {
return (
<input
type="text"
value={this.state.resource.email}
onChange={::this.handleFieldChanged} />
)
}
}
当this.state.resource.email
为空或未定义时,我遇到了一个问题,因为React不希望我将这些值作为值提供给受控组件:
Warning: `value` prop on `input` should not be null. Consider using the
empty string to clear the component or `undefined` for uncontrolled
components.
哪里是提供空字符串作为null
值的后备的合适位置?这应该在父组件的构造函数方法中完成吗?有没有一种方法可以避免显式地为每个可能具有null
值的属性执行此操作?
发布于 2017-02-01 04:44:40
我能想到的最简单的方法:
constructor (props) {
super(props)
this.state = {
resource: props.resource || {}
}
}
据我所知,没有办法自动设置这个值,使它们不为空,但如果有,我不建议这样做,好的代码是不言而喻的。
编辑1个
如果这还不够,那么另一个选择是直接从react的文档中使用uncontrolled components:
由于非受控组件将事实源保存在DOM中,因此在使用非受控组件时,有时集成React和非React代码会更容易。如果你想变得又快又脏,代码也可以稍微少一点。否则,您通常应该使用受控组件。
编辑2个
文档中提供的代码看起来有点令人费解,所以下面是我将如何做的一小段代码:
<input type="text" onChange={(e, val) => {this.setState({email: val})}} />
发布于 2017-02-01 04:37:54
您可以使用defaultValue
属性来设置初始值。
<input
type="text"
defaultValue={this.state.resource.email ? this.state.resource.email : ""}
onChange={this.handleFieldChanged} />
查看关于受控组件与非受控组件的优秀文档:https://facebook.github.io/react/docs/uncontrolled-components.html
https://stackoverflow.com/questions/41966935
复制相似问题