React报错 You provided a `value` prop to a form field without...

报错内容

Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. 
This will render a read-only field. If the field should be mutable use `defaultValue`. 
Otherwise, set either `onChange` or `readOnly`.

《React报错 You provided a `value` prop to a form field without...》

<PhoneInput
  key={key}
  label={item.label}
  name={key}
  disabled
  // readOnly
  value={this.state[key]}
  interCodeValue={this.state.intercode}
/>

原因

原因是因为input标签,没有定义onChange 但是提供了value属性。React会抛出警告,并将元素设置为只读。

如果目标是只读字段,最好使用readOnly属性明确加以定义。这不仅会消除警告,也会确保代码的可读性。

解决:

可以添加readOnly={true} ,或者直接添加readOnly属性,而不设置值,React会默认将该属性的值设为true。

    原文作者:Tenacity
    原文地址: https://segmentfault.com/a/1190000018019892
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞