【问题标题】:Add custom data- attribute to Option component react-select将自定义 data- 属性添加到 Option 组件 react-select
【发布时间】:2022-11-10 22:01:53
【问题描述】:

我正在使用react-select 库为我的下拉可搜索组件创建一个测试。
在自定义react-select documentation 中定义的组件时,我无法将data-testid 属性添加到Option 组件。

data-testid 属性不会显示在 Option 元素的 DOM 中。

选项组件

import Select, { components } from 'react-select';

const CustomOption = (props: OptionProps<SearchDropdownOption, false>) => (
  <components.Option {...props} data-testid="test-id" />
);

例如我有一个成功使用 Input 组件搜索下拉列表和 data-testid 属性在 DOM 中显示:

输入组件

import Select, { components } from 'react-select';

const CustomInput = (props: InputProps<SearchDropdownOption, false>) => (
  <components.Input {...props} data-testid="test-id" />
);

而不是在Select 组件中使用它:

<Select<SearchDropdownOption, false>
  components={{
    Input: CustomInput,
    Option: CustomOption,
  }}
  isSearchable={isSearchable}
/>

【问题讨论】:

    标签: reactjs testing components react-select


    【解决方案1】:

    像我为 Input 组件所做的那样,无法将自定义属性 data-testid 直接添加到 Option 组件。我需要使用 HTML span 元素或任何其他元素扩展此组件,并将此属性直接添加到该元素:

    const CustomOption = (props: OptionProps<SearchDropdownOption, false>) => {
      return (
        <components.Option {...props}>
          <span data-testid="test-id" key={props.innerProps.key}>
            {props.data.label}
          </span>
        </components.Option>
      );
    };
    

    笔记这个 key 属性很重要,因为它为元素和值提供了常规的 React 唯一性,可以从 react-select 的 innerProps 属性中使用:

    key={props.innerProps.key}
    

    【讨论】:

      【解决方案2】:
      const OptionWrapper = (customProps: IOptionProps) =>
        (nativeProps: OptionProps) => (
          <components.Option
            {...nativeProps}
            innerProps={{
              ...nativeProps.innerProps,
              ...customProps
            }}
          />
        );
      
      Option = OptionWrapper({ 'data-testid':"test-id" })
      

      尝试这个

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-15
        • 2011-09-20
        • 1970-01-01
        • 2019-07-19
        • 2010-12-03
        • 2020-06-19
        • 2021-12-21
        相关资源
        最近更新 更多