【问题标题】:How do you set the color of a disabled button using a react-native-paper theme?如何使用 react-native-paper 主题设置禁用按钮的颜色?
【发布时间】:2020-04-12 17:50:08
【问题描述】:

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 颜色有效。 禁用时如何更改按钮的颜色?

【问题讨论】:

    标签: react-native material-design react-native-paper


    【解决方案1】:

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

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

    【讨论】:

    • 很好的解决方案!! :)
    • 嗨!我认为这是一个很好的解决方案,但是当按钮被“禁用”时,如何禁用点击效果?谢谢你
    • 您的按钮组件必须具有类似 isDisabled 或类似的属性。请查看文档。
    【解决方案2】:

    来自Github issue

    如果包含的按钮的文本取决于背景颜色 按钮,它是根据 背景颜色是浅的它是深的。无论主题是否黑暗 不影响。

    这是期望的行为。我们不想在 浅色背景,因为您有深色主题,否则文本 对比度不够,难以辨认。

    将主题更改为深色 更改禁用按钮的颜色,正如我测试的那样。除此之外,如果您使用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' }}>
    

    【讨论】:

    • 谢谢,但这只会改变按钮中文本的颜色。
    • 以前不知道这个,这真的很有帮助,因为我可以直接通过 style 属性设置按钮背景颜色,但不知道如何更改内部文本的颜色。
    【解决方案3】:

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

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

    你可以在Css文件中添加

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

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

    【讨论】:

      【解决方案4】:

      如果你现在关心光明和黑暗的主题,那么你可以像这样实现你的目标 - 我建议在 Paper Button 的顶部创建自己的 Button 组件。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-19
        • 2022-09-26
        • 2023-01-08
        • 1970-01-01
        • 2021-10-25
        • 1970-01-01
        • 2020-02-26
        相关资源
        最近更新 更多