如何自动将新令牌添加到选择框?

时间:2019-05-14 10:49:39

标签: javascript reactjs select antd

我正在尝试将antdautomatic tokenization选择框用作:

 import { Select } from 'antd';

const Option = Select.Option;

const children = [];
for (let i = 10; i < 36; i++) {
children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

function handleChange(value) {
console.log(`selected ${value}`);
}

ReactDOM.render(
<Select mode="tags" style={{ width: '100%' }} onChange={handleChange} tokenSeparators={[',']}>
    {children}
</Select>,
mountNode,
);

现在,我想将令牌/标签动态添加到选择框中。标记化框如下所示:

enter image description here

我正尝试将新令牌推送为:

children.push(<Option key={newKey}>{newValue}</Option>

尽管如此,它进入了选择框,但未在框中显示为所选标记之一。我该怎么办?我必须手动选择添加的令牌。我希望添加的新令牌自动出现在选择框中。

1 个答案:

答案 0 :(得分:0)

您应该useState更新您的孩子:

import { Select, useState } from 'antd';

const Option = Select.Option;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

function SelectBox () {
  const [children, setChildren] = useState(children);
  return <Select mode="tags" style={{ width: '100%' }} onChange={(value) => setChildren([...children, value])} tokenSeparators={[',']}>
    {children}
  </Select>
}

ReactDOM.render(<SelectBox />, mountNode);

检查文档 here

这是这段代码的等效内容:

default class Select extends Component {
  constructor(props) {
    super(props);
    const children = [];
    for (let i = 10; i < 36; i++) {
      children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
    }
    this.setState({children});
  }
  render () {
    const { children } = this.state;
    return <Select mode="tags" style={{ width: '100%' }} onChange={(value) => this.setState({children: [...children, value]})} tokenSeparators={[',']}>
      {children}
    </Select>
  }
}