[英]defaultValue or value not working on FormItem ANTD
我尝试使用以下代码,但该字段永远不会被绑定。 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 时,不会反映更改。
文档指出:
您不能通过 value defaultValue 属性设置表单控件的值,而应该使用getFieldDecorator 中的 initialValue设置默认值。
您不应该手动调用 setState,请使用 this.props.form.setFieldsValue以编程方式更改值。
所以你只需要在后端加载数据时调用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)
对于类组件 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>
);
}
}
你也可以使用钩子
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.