<input> 标签上的 prop `value` 的值无效

IT技术 reactjs antd
2021-05-02 18:15:33

我收到无法解决的警告:

value标签上的props值无效要么将其从元素中移除,要么传递一个字符串或数字值以将其保留在 DOM 中。详情

以下是我正在使用的代码:

<FormItem validateStatus={NameError ? "error" : ""} help={NameError || ""}>
  {getFieldDecorator("Name", {
    initialValue: (()=>{this.state.Data.Name}),
    rules: [{ required: true, message: "Please input the component name!" }]
  })(
    <Input
      className="form-control"
      type="text"
      name="Name"
      defaultValue={this.state.Data.Name}
      onChange={this.onChange}
    />
  )}
</FormItem>

我的typescript界面如下所示:

export interface IFieldEdition{
    Data:IFieldData
}

export interface IFieldData{
    Id?:number,
    Name?:string,
    Value?:string,
    Description?:string,
    CreatedDate?:Date,
    CreatedBy?:string,
    StatusId?: number
}

我该如何解决这个问题?有什么线索吗?

3个回答

我看到您正在使用 antd 表单。来自 antd form官方文档

被getFieldDecorator包裹后,value(或valuePropName定义的其他属性)onChange(或trigger定义的其他属性)props会被添加到表单控件中,表单数据的流向会被Form处理,导致:

您不应该手动调用 setState,请使用 this.props.form.setFieldsValue 以编程方式更改值。

您使用initialValue: (()=>{this.state.Data.Name}, 调用 setState 可能是您收到此错误的原因。

不确定它是如何getFieldDecorator工作的,但似乎问题在于您将函数作为initialValueprops传递

尝试替换initialValue: (()=>{this.state.Data.Name})initialValue: this.state.Data.Name

我在制作带有输入的表单时看到了这个错误,就我而言,解决方案非常简单:

<input 
    type="text" 
    value={this.state.term} 
    onChange={(e) => this.setState({ term: e.target.value.toLocaleUpperCase() })}
/>

发生的事情是我只是忘记调用该方法并且是这样的:

toLocaleUpperCase

所以,不要忘记任何函数调用末尾的括号。希望这可以帮助。