【问题标题】:How to send State in Styling API as a Props for Custom Resuable ReactSelect?如何在样式 API 中发送状态作为自定义可重用 React Select 的道具?
【发布时间】:2021-12-09 08:41:58
【问题描述】:

我有默认样式的全局 ReactSelect。我只需要覆盖样式的一个属性。将以下内容视为可重用的 CustomReactSelect 组件。

custom-react-select.tsx

export const CustomReactSelect = (props) => {
const defaultStyle = {
 control: (provided, state) => ({
            ...
            backgroundColor: (state.isDisabled) ? '--theia-editorGroupHeader-tabsBackground' : 'var(--theia-input-background)',
            fontSize: 'var(--theia-ui-font-size1)',
            ...
        }),
} 
 ...
return <Select 
              ...
              styles = {...defaultStyle,...props.style}
              ...
              />
}

考虑一种情况,我只需要以类似的方式覆盖控件样式的背景。

const overrideControlStyle = {
        backgroundColor: (state.isFocused) ? 'red' : 'black'
}

我只需要覆盖backgroundColor,最后应该发送到React Select的props应该如下,

Sent Props...
{
 control: (provided, state) => ({
            ...
            backgroundColor: (state.isFocused) ? 'red' : 'black',
            fontSize: 'var(--theia-ui-font-size1)',
            ...
        }),
} 

【问题讨论】:

    标签: javascript css reactjs typescript react-select


    【解决方案1】:

    你在正确的轨道上。 provided 是当前选择特定组件的默认样式,因此您的样式需要与它们合并。

    (provided, state) => ({
      ...provided,
      backgroundColor: 'black',
      ...(state.isFocused && {
        backgroundColor: 'red'
      }),
      ...(state.isDisabled && {
        backgroundColor: 'var(--theia-editorGroupHeader-tabsBackground)'
      })
    })
    

    因此,请考虑您的重要性与覆盖的顺序。您最后定义的任何条件都将获胜。如果控件被聚焦,那么backgroundColor 将是红色的,但是isDisabledisFocused 更重要,所以最后定义它会使用变量。

    这可能不适合您的用例,但希望能让您走上正确的道路。

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 2022-01-23
      • 2020-08-31
      • 2023-03-31
      • 2021-03-25
      • 1970-01-01
      • 2018-02-28
      • 1970-01-01
      • 2019-07-21
      相关资源
      最近更新 更多