繁体   English   中英

使用 ant 设计 Select 组件在 React JS 中自动 select onBlur

[英]auto select onBlur in React JS using ant design Select component

我有以下代码

我正在尝试执行以下操作。 当用户在输入中输入内容时,它应该被添加到我的 onBlur 数组中。 那部分工作得很好。 现在除了添加到数组之外,我还希望它自动被选中。 我该如何实现呢?

    import React, { useState } from "react";
    import "antd/dist/antd.css";
    import "./index.css";
    import { Select } from "and";

    const { Option } = Select;
    const arr = ["1", "2", "3"];
    const App = () => {
      const [data, setData] = useState(arr);

      return (
       <>
      <Select
        mode="tags"
        size={"large"}
        placeholder="Please select"
        style={{
          width: "100%"
        }}
      >
        {data?.map((el) => (
          <Option key={el} value={el}>
            {el}
          </Option>
        ))}
         </Select>

          <input onBlur={(e) => setData([...data, e.target.value])} />
        </>
      );
    };

    export default App;


请帮我解决这个问题。

您需要控制Select组件的children项( data )和value

您可以通过使用valueonChange道具来控制Select组件的 state ,如下所示:

import React, { useState } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Select } from "antd";

const { Option } = Select;
const arr = ["1", "2", "3"];
const App = () => {
  const [data, setData] = useState(arr);
  const [value, setValue] = useState([]);

  const handleTextBlurred = (e) => {
    const newVal = e.target.value;
    if (!data.includes(newVal)) {
      setData([...data, newVal]);
    }
    if (!value.includes(newVal)) {
      setValue([...value, newVal]);
    }
  };

  return (
    <>
      <Select
        mode="tags"
        size={"large"}
        placeholder="Please select"
        style={{
          width: "100%"
        }}
        value={value}
        onChange={(newVal) => setValue(newVal)}
      >
        {data?.map((el) => (
          <Option key={el} value={el}>
            {el}
          </Option>
        ))}
      </Select>

      <input onBlur={handleTextBlurred} />
    </>
  );
};

export default App;

您可以查看这个分叉的沙箱,了解该解决方案的实时工作示例。

暂无
暂无

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

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