gpt4 book ai didi

javascript - react | Ant design 选择默认值

转载 作者:数据小太阳 更新时间:2023-10-29 05:43:54 25 4
gpt4 key购买 nike

我正在使用 ant design在我的项目中。

这里我有一个选择作为动态字段。当我尝试为选择设置默认值时。它不起作用。

<Select defaultValue="lucy">
<Option value="jack">Jack</Option>
<Option value="lucy">Lucy</Option>
<Option value="Yiminghe">yiminghe</Option>
</Select>

我将默认值设置为 lucy 但它不起作用

复制代码:https://codesandbox.io/s/6x3qv6wymr

最佳答案

根据documentation ,您不应将 valuedefaultValuegetFieldDecorator 一起使用。

After wrapped by getFieldDecorator, value(or other property defined by valuePropName) onChange(or other property defined by trigger) props will be added to form controls,the flow of form data will be handled by Form which will cause:

  1. You shouldn't use onChange to collect data, but you still can listen to onChange(and so on) events.

  2. You can not set value of form control via value defaultValue prop, and you should set default value with initialValue in getFieldDecorator instead.

  3. You shouldn't call setState manually, please use this.props.form.setFieldsValue to change value programmatically.

因此,在您的代码中,您需要定义 initialValue 而不是 defaultValue,如下所示:

{getFieldDecorator(`names[${k}]`, {
validateTrigger: ["onChange", "onBlur"],
initialValue: "lucy",
rules: [
{
required: true,
whitespace: true,
message: "Please input passenger's name or delete this field."
}
]
})(
<Select>
<Option value="jack">Jack</Option>
<Option value="lucy">Lucy</Option>
<Option value="Yiminghe">yiminghe</Option>
</Select>
)}

您可以在 codesandbox.io 上查看工作演示.

关于javascript - react | Ant design 选择默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52425293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com