反应选择自定义标题

时间:2019-10-15 10:52:54

标签: reactjs react-select

如何使用react select来为选定的值设置自定义组件,我能够自定义选项,但是选定的选项本身又如何与选定的组件具有相同的选定组件也很聪明,有什么想法吗?

<Select 
 components={{ Option: CustomOption }}
 options={options} 
 styles={customStyles} 
/>;

组件:

    const CustomOption =  ({ value, label, innerProps, innerRef }) => (
        <div ref={innerRef {...innerProps}>
        <img src={label === 'En' ? pngEn : label === 'Ru' ? pngRu : pngLt} />
       <div>{label}</div>
</div>
);

编辑,下面是选项,我想看到该标志,然后选择选项,那可能是因为自定义选项:

const options = [
  { value: "lt", label: "Lt" },
  { value: "en", label: "En" },
  { value: "ru", label: "Ru" },
];

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为最简单的方法是按照自定义的方式使用自定义Option组件,并在options内存储一个额外的道具,以获取想要显示的图片。 / p>

在下面的示例中,使用react-icons库而不是使用图像,但是想法是相同的:

const Option = props => {
  const CComponent = props.data.icon;
  return (
    <div style={{ display: "flex" }}>
      <CComponent />
      <components.Option {...props} />
    </div>
  );
};
const options = [
  { label: "Option 1", value: 1, icon: FaOpera },
  { label: "Option 2", value: 2, icon: FaFirefox },
  { label: "Option 3", value: 3, icon: FaInternetExplorer }
];

function App() {
  return (
    <div className="App">
      <Select options={options} components={{ Option }} />
    </div>
  );
}

实时示例here