html 添加 "value" 参数后输入不可编辑

html input is not editable when added "value" parameter

我正在使用 React 16。我有一个输入字段需要从我的数据库中填充一个值,我需要它是可编辑的。

如果我使用:

<FormControl type="text" ref="price" id="precio" value={this.state.precioVenta} />

输入字段填充值但不允许我编辑。我试过了

<FormControl type="text" ref="price" id="precio" defaultValue={this.state.precioVenta} />

但它不会填充值

你需要处理变化。如果您简单地设置值,它将始终设置为:

<FormControl 
  type='text'
  name='precio' 
  defaultValue={this.state.precioVenta}
  onChange={this.handleChange.bind(this)}
/>

handleChange(event) {
    let fieldName = event.target.name;
    let fieldVal = event.target.value;
    this.setState({...this.state, [fieldName]: fieldVal})
}

有什么理由不只使用 placeholder 而不是值? <FormControl type="text" ref="price" id="precio" placeholder={this.state.precioVenta} />

这看起来像是一个典型的状态更新问题。你在哪里更新你的状态?我想您需要手动处理输入更改:

<FormControl type="text" value={this.state.precioVenta} onChange={this.handlePrecioChange} />

哪里

handlePrecioChange(event) {
  this.setState({ precioVenta: event.target.value }, () => {
    this.validatePrecioVenta(); // if needed
  });
}

并且不要忘记将组件的实例上下文绑定到组件的构造函数上,以使处理程序内部的 this 正常工作:

constructor {
  this.handlePrecioChange = this.handlePrecioChange.bind(this);
}