react-select 我想在选项中显示和图像。但是当我选择该选项时,我希望控件仅显示该选项的文本部分

问题描述 投票:0回答:1

这是选项和formatOptionLabel函数

  const brandOptions = films.map((film) => ({
    value: film.brand,
    label: film.brand,
  }))

  const formatOptionLabel = ({ value, label, isSelected }) => (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      {isSelected ? null : (
        <img
          src={films.find((film) => film.brand === value)?.brandpic}
          alt={value}
          style={{ marginRight: '8px', width: '20px', height: '20px' }}
        />
      )}
      {label}
    </div>
  )

这是下拉菜单

    <ReactSelect
            value={brandOptions.find((option) => option.value === selectedBrand)}
            onChange={handleBrandChange}
            options={brandOptions}
            placeholder="choose the brand"
            formatOptionLabel={formatOptionLabel}
            className="bg-white ml-5 rounded-[40px] border-[#EBEBEB] shadow-sm w-[278px]"
          />

选项带有图像和品牌名称。但问题是,当我单击选择选项时,我只想在控件中显示品牌名称。该代码为我提供了图像和品牌名称。

const formatOptionLabel = ({ value, label, isSelected }) => (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      {isSelected ? null : (
        <img
          src={films.find((film) => film.brand === value)?.brandpic}
          alt={value}
          style={{ marginRight: '8px', width: '20px', height: '20px' }}
        />
      )}
      {label}
    </div>
  )

{已选择? null :( ...部分似乎没有效果

reactjs dropdown react-select
1个回答
0
投票

formatOptionLabel
将菜单和控件中的选项标签格式化为 React 组件

formatOptionLabel
箭头功能检查上下文以确定选项是否显示在下拉菜单中或控件中。如果该选项位于下拉菜单中,则它包含图像。如果该选项位于控件中,则意味着它已被选择,那么它只显示标签。

const formatOptionLabel = ({ value, label }, { context }) => {
    const film = films.find((film) => film.brand === value);
    return (
      <div style={{ display: "flex", alignItems: "center" }}>
        {context === "menu" ? (
          <img
            src={film?.brandpic}
            alt={value}
            style={{ marginRight: "8px", width: "20px", height: "20px" }}
          />
        ) : null}
        {label}
      </div>
    );
  };

如果您想尝试示例代码

© www.soinside.com 2019 - 2024. All rights reserved.