这是Options和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]"
          />

这些选项既有品牌名称,也有形象.但问题是,当我单击以 Select 该选项时,我只希望在控件中显示品牌名称.这个代码既给了我形象也给了我品牌名称.

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>
  )

{被选中了吗?空:(...部分似乎没有效果

推荐答案

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>
    );
  };

如果你想玩code号样品的话.

Reactjs相关问答推荐

两条react 路由的行为不同.有没有人能解释一下,我已经找了好几天了

如何在REACTIVE js中动态添加或删除输入字段?

透明MOV文件未出现在我的React网页中

如何将 npm 包添加到我的 Vite + React 应用程序中?

解决在React测试库中的act()警告

ReactJS on AWS Amplify与EC2上的Spring boot服务之间的混合内容错误

如何将 DocuSign 控制台界面嵌入到 React 应用中

Zod 验证模式根据另一个数组字段使字段成为必需字段

有没有办法在用户离开页面时防止输入模糊?

Formik onChange() 字段挂钩覆盖显示值和 Select 机制

如何在 ReactJS 中提交后删除 URL 中的查询参数

表单错误后 Ionic React 无法 Select 单选按钮

在 redux 中分派到另一个减少时状态值不会改变

ReactJS:useMemo 钩子修复了我的无限重新渲染问题而不是 useEffect

是什么导致了这个令人惊讶的数组导致 React

用 scss 覆盖 MUI

React如何在用户登录后等待当前用户数据被获取

RTK 查询 POST 方法不会改变数据

错误(未捕获的类型错误):无法读取未定义的属性(读取参数)

如何判断对话框组件是否位于对话框之上?