[英]#Antd# How can I bind self-made component with Form.item
I want to use my component like this我想像这样使用我的组件
<Form.item>
<MyComponent />
</Form.item>
I can't pass the defaultValue to MyComponent and the Form can't get the value from MyComponent when I hit the submit button.当我点击提交按钮时,我无法将 defaultValue 传递给 MyComponent 并且表单无法从 MyComponent 获取值。
How can I fix this?我怎样才能解决这个问题?
For using a default value you can use initialValues
from antd's Form
together with the in Form.Item
defined name
.要使用默认值,您可以使用 antd 的Form
中的initialValues
以及Form.Item
中定义的name
。
Eg:例如:
<Form
{...layout}
name="basic"
initialValues={{
myComponent: "IntialTestValue"
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="MyComponent"
name="myComponent"
To use custom or third party component you need bind your component to a value
and onChange
.要使用自定义或第三方组件,您需要将您的组件绑定到一个value
和onChange
。
Eg:例如:
const MyComponent = ({ value = {}, onChange }) => {
const [inputValue, setInputValue] = useState(value);
const onInputChange = e => {
setInputValue(e.target.value);
onChange(e.target.value);
};
return (
<>
<Input defaultValue={value} value={inputValue} onChange={onInputChange} />
</>
);
};
Here is a working CodeSandbox .这是一个有效的CodeSandbox 。
Another good example can be found int antd Form docs : CodeSandbox另一个很好的例子可以在 int antd Form docs中找到: CodeSandbox
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.