【问题标题】:react-select: Is it possible to add animated components and custom components simultaneously?react-select:是否可以同时添加动画组件和自定义组件?
【发布时间】:2021-07-30 04:34:01
【问题描述】:

我想知道是否可以在 Select 组件内的 components 道具中同时添加动画组件和自定义组件。 不幸的是,在 react-select 文档中找不到任何内容。

对于“动画组件”,我指的是这些:https://react-select.com/home#animated-components

“自定义组件”是:https://react-select.com/components#replaceable-components

在我的例子中,自定义组件是这个:

// Custom component
const CustomMultiValue = (
    props: MultiValueProps<FilterOptions, GroupTypeBase<FilterOptions>>
  ) => (
    <components.MultiValue {...props}>{props.data.label}</components.MultiValue>
  );

// Animated components
  const animatedComponents = makeAnimated();

Select 看起来像这样:

<Select
      isMulti
      onChange={(value) => handleChange(value)}
      styles={customSelectStyles}
      components={{ MultiValue: CustomMultiValue }}
      theme={customSelectTheme}
      closeMenuOnSelect={false}
      placeholder={placeholder}
/>

我尝试了很多方法来添加动画组件,但似乎没有任何效果。 例如:

components={animatedComponents, { MultiValue: CustomMultiValue }}

components={{ MultiValue: CustomMultiValue, Control: animatedComponents }}

有人有想法吗? 谢谢!

【问题讨论】:

    标签: reactjs react-select


    【解决方案1】:

    我假设您想要自定义 MultiValue 组件以使其具有动画效果。

    您可以在动画组件的文档中看到,makeAnimated 方法为作为参数传递的组件创建了一个包装器,并且:

    If no arguments are passed, built-in components are wrapped instead.

    在您的代码中,这是内置的 MultiValue 组件,它将被动画化

    如果这是您想要的,您必须将自定义 MultiValue 作为参数传递给 makeAnimated,并在 Select 的 components 属性中使用 animatedComponents

    // Animated components
      const animatedComponents = makeAnimated({ MultiValue: CustomMultiValue });
    
    ...
    
    <Select
          isMulti
          components={animatedComponents}
          ...
    />
    

    您可以在此代码沙箱中尝试它,其中 MultiValue 被动画和自定义以显示自定义标签

    https://codesandbox.io/s/clever-payne-ehi8t?file=/src/App.tsx

    【讨论】:

    • 嘿哥拉祖!感谢您的可靠回答,我很感激!该解决方案在代码框中运行良好,但在我的项目中却不起作用。不知道为什么。 ?
    • 更新:我不知道究竟是为什么,但我注意到它现在可以工作了。非常感谢@gorazu!
    • 不错!很高兴它帮助了你?
    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 2014-10-14
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多