我正在尝试使用户配置文件在我的组件中可编辑。现在,当用户单击“编辑”时,配置文件就会被替换为一个表单,其中包含他们输入的默认值。但是,如果它们只更新一个字段,则会用空值重写其他字段,而不是将默认值传递给状态。
有没有一种方法可以将defaultValue传递给状态?我也尝试过value={},但是值根本不变。
我尽量避免每个输入都有一个“编辑”按钮。
class AccountEditor extends Component {
constructor() {
super()
this.state = {
isEditing: false,
profile: {
firstName: '',
lastName: '',
city: '',
email: '',
bio: '',
}
}
}
toggleEdit(event) {
event.preventDefault()
this.setState({
isEditing: !this.state.isEditing
})
}
updateProfile(event) {
let updatedProfile = Object.assign({}, this.state.profile)
updatedProfile[event.target.id] = event.target.value
this.setState({
profile: updatedProfile
}
}
submitUpdate(event) {
event.preventDefault()
this.props.onUpdate(this.state.profile)
this.setState({
isEditing: !this.state.isEditing
})
}
render() {
let profile = this.props.profile
let content = null
if (this.state.isEditing == true) {
content = (
<div>
<input
id="firstName"
onChange={this.updateProfile.bind(this)}
defaultValue={profile.firstName} />
<br />
<input
id="lastName"
onChange={this.updateProfile.bind(this)}
defaultValue={profile.lastName} />
<br />
<input
id="city"
onChange={this.updateProfile.bind(this)}
defaultValue={profile.city} />
<br />
<input
id="email"
onChange={this.updateProfile.bind(this)}
defaultValue={profile.email} />
<br />
<textarea
id="bio"
onChange={this.updateProfile.bind(this)}
defaultValue={profile.bio} />
<br />
<button onClick={this.submitUpdate.bind(this)}>Done</button>
</div>
)
} else {
content = (
<div>
<h4>Name: </h4>
<span>{profile.firstName}</span>
<span>{profile.lastName}</span><br/>
<h4>City: </h4>
<span>{profile.city}</span><br/>
<h4>Bio :</h4>
<p>{profile.bio}</p><br />
<button onClick={this.toggleEdit.bind(this)}>Edit</button>
</div>
)
}
return (
<div>
{content}
</div>
)
}
}
export default AccountEditor发布于 2017-03-13 01:59:30
您应该用value = { this.state.someProp }替换defaultValue。因此,您的代码的示例如下
constructor(props) {
super(props)
this.state = {
isEditing: false,
profile: props.profile // Setting up the initial data from the passed prop
}
}和
<input id="firstName"
onChange={ this.updateProfile.bind(this) }
value={ this.state.profile.firstName } />有关在these docs中使用react和表单元素的更多信息。
https://stackoverflow.com/questions/42750980
复制相似问题