无法使用defaultValue设置React状态

时间:2017-03-12 17:51:34

标签: javascript reactjs

我尝试在我的组件中编辑用户个人资料。现在,当用户点击"编辑时,"该配置文件将替换为具有默认值输入值的表单。但是,如果它们仅更新一个字段,则其他字段将使用空值重写,而不是将默认值传递给该状态。

有没有办法将defaultValue传递给状态?我也试过了值= {},但价值根本没有变化。

我试图避免使用"编辑"每个输入的按钮。

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

1 个答案:

答案 0 :(得分:4)

您应该将defaultValue替换为value = { this.state.someProp }。所以你的代码的例子是

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中的表单元素进行反应的更多信息。

相关问题