gpt4 book ai didi

reactjs - defaultValue 或值不适用于 FormItem ANTD

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:52 24 4
gpt4 key购买 nike

我尝试使用以下代码,但该字段从未绑定(bind)。 onChange 属性运行良好

const { getFieldDecorator, getFieldError, isFieldTouched } = this.props.form;
const NameError = isFieldTouched("Name") && getFieldError("Name");

<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>

我错过了什么吗?我什至使用 input 而不是 Input

编辑componentDidMount 方法中,我从 API 获取数据:

fetch('http://localhost:5728/Fields/get/' + this.state.Data.Id)
.then(results=>{
return results.json()
})
.then(data=>{

this.setState({
Data: {
Id: data.field.Id,
Name: data.field.Name,
Description: data.field.Description,
Value: data.field.Value
}
})

})

我试过使用 initialValue,但只有在 constructor 方法上设置状态值时它才有效。调用 API 时,不会反射(reflect)更改。

最佳答案

docs states那:

You cannot set value of form control via value defaultValue prop, and you should set default value with initialValue in getFieldDecorator instead.

You shouldn't call setState manually, please use this.props.form.setFieldsValue to change value programmatically.

所以你只需要在后台加载数据的时候调用setFieldsValue即可:

fetch('http://localhost:5728/Fields/get/' + this.state.Data.Id)
.then(results=>{
return results.json()
})
.then(data=>{

this.props.form.setFieldsValue({
Id: data.field.Id,
Name: data.field.Name,
Description: data.field.Description,
Value: data.field.Value
})
})

或者更短,如果来自后端的 data.field 完全匹配字段名称:

this.props.form.setFieldsValue(data.field)

关于reactjs - defaultValue 或值不适用于 FormItem ANTD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53182493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com