[英]defaultValue or value not working on FormItem ANTD
I tried using the following code and the field never gets bind.我尝试使用以下代码,但该字段永远不会被绑定。 The onChange property works well
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>
Am I missing something?我错过了什么吗? I even used
input
instead of Input
我什至使用
input
而不是Input
EDIT On componentDidMount
method I get the data from an API:编辑在
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
}
})
})
I tried using initialValue
, but it only works when the state value is set on the constructor
method.我尝试使用
initialValue
,但它仅在constructor
方法上设置状态值时才有效。 When calling the API, the change is not reflected.调用 API 时,不会反映更改。
The docs states that:文档指出:
You cannot set value of form control via value defaultValue prop, and you should set default value with initialValue in getFieldDecorator instead.
您不能通过 value defaultValue 属性设置表单控件的值,而应该使用getFieldDecorator 中的 initialValue设置默认值。
You shouldn't call setState manually, please use this.props.form.setFieldsValue to change value programmatically.
您不应该手动调用 setState,请使用 this.props.form.setFieldsValue以编程方式更改值。
So you just need to call setFieldsValue
when the data is loaded from the backend:所以你只需要在后端加载数据时调用
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
})
})
Or shorter, if data.field
from backend totally matches the field names:或者更短,如果后端的
data.field
完全匹配字段名称:
this.props.form.setFieldsValue(data.field)
For Class component V4:对于类组件 V4:
class Demo extends React.Component {
formRef = React.createRef();
componentDidMount() {
this.formRef.current.setFieldsValue({
username: 'Bamboo',
});
}
render() {
return (
<Form ref={this.formRef}>
<Form.Item name="username" rules={[{ required: true }]}>
<Input />
</Form.Item>
</Form>
);
}
}
you can use hook, too你也可以使用钩子
import { Form } from "antd"
const [form] = Form.useForm();
fetch('api')
.then(results=>{
return results.json()
})
.then(data=>{
form.setFieldsValue({
sample: data.dataYouWant
});
<Form form = {form}>
<Form.Item name = "sample">
<Input />
</Form.Item>
</Form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.