简体   繁体   English

反应 | Ant 设计 select 值未设置

[英]React | Ant design select value not setting

I am trying to add Select All / Unselect All to React Antd's 'SELECT' component.我正在尝试将 Select All / Unselect All 添加到 React Antd 的“SELECT”组件中。

My code我的代码

const models = ['A4', 'A6', 'A8', 'A1', 'Q3', 'Q5'];
const [selected, setSelected] = useState({
  models: [],
});

console.log('selected', selected);

const handleModelSelect = (option) => {
  if (option === 'all') {
    if (selected.models.length === models.length) {
      setSelected((prev) => ({ ...prev, models: [] }));
    } else {
      setSelected((prev) => ({ ...prev, models }));
    }
  } else {
    setSelected((prev) => ({ ...prev, models: uniq([...prev.models, option]) }));
  }
};

return
(<Form>
  <Form.Item
    name="model"
    style={{ display: 'inline-block', width: 'calc(33% - 8px)' }}
  >
    <Select mode="multiple" placeholder="Models" value={selected.models} onSelect={handleModelSelect}>
      <Option value="all">Select all</Option>
      {map(models, model => <Option value={model} key={model}>{model}</Option>)}
    </Select>
  </Form.Item>
</Form>)

I see that I do get everything selected & unselected in the "selected.models", however the issue is that the Select component visually does NOT update itself, meaning it stays with things I have selected/unselected.我看到我确实在“selected.models”中选择和取消选择了所有内容,但是问题是 Select 组件在视觉上不会自我更新,这意味着它会保留我选择/取消选择的内容。

Really weird behavior.真是奇怪的行为。

The issue was with using Antd's Form & Form.item along with Select .问题在于使用 Antd 的Form & Form.item以及Select Code works perfectly fine without the Form没有表单,代码工作得很好

Because the models variable is unchanged.因为models变量没有改变。 You could apply the below two changes:您可以应用以下两个更改:

One

const models = ['A4', 'A6', 'A8', 'A1', 'Q3', 'Q5'];
const [selected, setSelected] = useState({
  // Initial state
  models,
});

Two

// Get models from `selected`
{map(selected.models, model => <Option value={model} key={model}>{model}</Option>)}

Alex answer is correct.亚历克斯的回答是正确的。 For anyone who need Form.item as parent for Select - it is possible with custom form components .对于需要Form.item作为Select的父级的任何人 - 可以使用自定义表单组件 Just create your custom component that render antd Select.只需创建呈现 antd Select 的自定义组件。 And paste your component as only child to Form.item (without any nested elements or wrappers)并将您的组件作为唯一的子组件粘贴到Form.item (没有任何嵌套元素或包装器)

<Form.Item>
    <MySelect />
</Form.Item>

Your custom component will automatically receive value and onChange as props.您的自定义组件将自动接收valueonChange作为道具。 And you can also pass in additional your own props to your custom component.您还可以将其他自己的道具传递给您的自定义组件。 For example field name or data - an array of options for select.例如字段名称数据- select 的选项数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM