I tried using the following code and the field never gets bind. The onChange property works well
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
EDIT
On componentDidMount method I get the data from an 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. When calling the API, the change is not reflected.
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.
You shouldn't call setState manually, please use this.props.form.setFieldsValue to change value programmatically.
So you just need to call setFieldsValue when the data is loaded from the backend:
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:
this.props.form.setFieldsValue(data.field)
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>
For Class component 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>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With