如何使用 react-native-paper 主题设置禁用按钮的颜色?

How do you set the color of a disabled button using a react-native-paper theme?

react-native-paper docs建议你可以使用主题设置禁用按钮的颜色,但此代码不起作用:

export const buttonTheme = {
  colors: {
    primary: COL_BASE_YELLOW,
    disabled: COL_DARK_HIGHLIGHT,
  },
}

<Button
  loading={submittedPhoneNumber ? true : false}
  mode="contained"
  onPress={() => handleSubmitPhoneNumber(phoneNumber)}
  theme={buttonTheme}
  disabled={phoneNumber.length < 5 ? true : false}>
  Continue
</Button>

但是 primary 颜色有效。 禁用时如何更改按钮的颜色?

从这个Github issue:

The text if the contained button depends on the background color of the button, which is automatically determined based on of the background color is light it dark. Wherever theme is dark or not doesn't affect it.

This is the desired behavior. We don't want to show white text on a light background because you have a dark theme, otherwise the text won't have enough contrast and will be illegible.

将主题更改为深色 更改 禁用按钮的颜色,正如我测试的那样。除此之外,我认为如果使用 react-native-paper 是不可能的。作者已经决定根据一些东西自动设置按钮的颜色&背景颜色,但是他的语言不清楚

但是,您可以直接给按钮一个 labelStyle 道具,并且您可以在那种样式中有一个条件。

 <Button labelStyle={{ color: phoneNumber.length < 5 ? 'red' : 'green' }}>

或者,

[buttonDisabled, setButtonDisabled] = useState(false); // put this outside the render function.
<Button disabled={disabled} labelStyle={{ color: disabled ? 'red' : 'green' }}>

不要使用禁用的道具,它总是会让你的按钮变成灰色,如果你想在禁用模式下使用你想要的颜色,这样做:

<Button
  loading={submittedPhoneNumber ? true : false}
  mode="contained"
  onPress={phoneNumber.length < 5 ? () => {} : () => handleSubmitPhoneNumber(phoneNumber)}
  color={phoneNumber.length < 5 ? 'darkerColor' : 'fadedColor'}>
  Continue
</Button>

我可能迟到了,但这是我的解决方案:

<Button 
   id="save-phonenumber"
   color="darkColor">
   onClick={doSomething}
   disabled={phoneNumber.length < 5 ? true : false}>
<Button/>

在你的Css文件中你可以添加

Button#save-phonenumber[disabled] {
  background: "fadedColor"
}

使用这种方法的好处是当按钮被禁用时,您不需要另外禁用点击效果。

如果您目前关心浅色和深色主题,那么您可以像这样实现您的目标 - 我建议在 Paper Button 的顶部创建您自己的 Button 组件。

// extending default Paper Button Component
<PaperButton style={[ props.disabled && { backgroundColor: 'cccccc' } ]}>
  {children}
</PaperButton>


// Using component...
<MyButton disabled={disabled}>
  Click Me!
</MyButton>