如何在样式 API 中发送状态作为自定义可重用 React Select 的道具?

How to send State in Styling API as a Props for Custom Resuable ReactSelect?

我正在使用默认样式的全局 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的道具应该如下,

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

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

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

因此请考虑您的优先顺序。您最后定义的条件将获胜。如果控件获得焦点,则 backgroundColor 将为红色,但是 isDisabledisFocused 更重要,因此最后定义它会使用变量。

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