【问题标题】:How to use react-icons with select-option form element?如何使用带有选择选项表单元素的反应图标?
【发布时间】:2022-01-02 16:18:50
【问题描述】:

我想知道是否可以将 react-icons 与 select-option 元素一起使用。我在谷歌上搜索了很多关于这个问题的信息,但所有的解决方案都与 react-select 库有关,而不是简单的 select-option 元素。

这就是我正在做的事情

import {ReactIcon} from "react-icons";
.............
 some code here
.............
<select> 
    <option> sometext <ReactIcon /> </option>
   <option>  sometext <ReactIcon /> </option>
</select>

结果:

sometext [Object object]
sometext [Object object]

我想要什么:

sometext {the icon itself}  
sometext {the icon itself}

谢谢

【问题讨论】:

    标签: reactjs react-icons


    【解决方案1】:

    仅支持将字符串和数字作为&lt;option&gt; 子级。因此图标未呈现。

    您需要使用 React Select 组件,例如 react-select。这适用于react-icons

    具有上述组件的工作示例:

    import Select from "react-select";
    import {
      AiFillAlert,
      AiFillAlipayCircle,
      AiFillContainer
    } from "react-icons/ai";
    import { useState } from "react";
    
    export default function App() {
      const [selectedOption, setSelectedOption] = useState(null);
      // The label supports JSX.
      const options = [
        {
          value: "chocolate",
          label: (
            <div>
              <AiFillAlert /> Chocolate
            </div>
          )
        },
        {
          value: "strawberry",
          label: (
            <div>
              <AiFillAlipayCircle /> Strawberry
            </div>
          )
        },
        {
          value: "vanilla",
          label: (
            <div>
              <AiFillContainer /> Vanilla
            </div>
          )
        }
      ];
    
      return (
        <div className="App">
          <Select value={selectedOption} options={options} />
        </div>
      );
    }
    

    上面的代码渲染了以下组件:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2012-09-09
      • 1970-01-01
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多