Fle*_*ano 9 typescript reactjs 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>
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?我什至用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
}
})
})
Run Code Online (Sandbox Code Playgroud)
我尝试使用initialValue,但它仅在 constructor 方法上设置了状态值时才有效。调用 API 时,不会反映更改。
Ale*_*lex 16
该文档的状态是:
您不能通过 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
})
})
Run Code Online (Sandbox Code Playgroud)
或者更短,如果data.field来自后端的字段名称完全匹配:
this.props.form.setFieldsValue(data.field)
Run Code Online (Sandbox Code Playgroud)
小智 6
你也可以使用钩子
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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19476 次 |
| 最近记录: |