现在,我正在为我的应用程序使用react-native-elements组件库。具体来说,我使用的是它们的Button组件,该组件具有默认的灰色。
如何为这些按钮设置自定义默认颜色,而不必每次都传递样式道具?
有没有可以调用的简单函数/方法,还是我必须研究创建一个自定义组件来包装它?我希望前者。
我知道这是一个老问题,但是自从我找到了这篇文章以来,我将在这里留下这个答案供其他人查看。
自2018年10月以来,react-native-elements支持主题。根据文档,您可以在RN应用程序中使用主题提供程序,并通过执行以下操作来覆盖库的默认颜色:
import { ThemeProvider } from 'react-native-elements';
const theme = {
  colors: {
    primary: 'pink',
  }
}
....
....
render(){
  ...
  return(
      <ThemeProvider theme={theme} >
         <App/>
      </ThemeProvider>
   )
}
上面的示例将更改所有组件的原色。通过应用相同的逻辑,您可以仅更改按钮元素的背景颜色。您还可以将主题设置用于其他自定义,例如默认组件属性等。有关更多信息,请查看文档
相反,如果有人想改变特定组件的颜色
您可以使用 Button 组件的 buttonStyle 属性。在其中,您可以像平常一样设置样式,例如背景颜色和颜色
  import {Button} from 'react-native-elements'
  <Button
      buttonStyle={{
         backgroundColor: "red"
      }}
      containerStyle={{
         marginTop: 12,
         width: "40%"
      }}
      title="Cancel"
   />
查看官方文档:https://react-native-elements.github.io/react-native-elements/docs/button.html#buttonstyle
我现在继续制作一个包装类。如果有人发现如何以其他方式做到这一点,请发帖。
为此,我执行了以下操作
-从react-native-elements导入Button类
import {Button} from 'react-native-elements'
-创建了一个组件类,我在其中传递了从react-native-elements发送到原始按钮的所有相同道具。
class ButtonCustom extends Component{    
    constructor(props) {
      super(props)
    }
    render(){
      return (
        <Button 
        {...this.props} 
        backgroundColor={this.props.backgroundColor|| 'blue' } /> 
        //this allows me to override that backgroundColor if i need to
      )
    }  
}
- 将其导出为模块以便于重用
module.exports = ButtonCustom;
每当我需要它时,我只需导入并使用它即可。我至少不需要每次都设置样式,如果需要,我可以进行全局更改。
<ButtonCustom
          title="Blue Automatically"
          />
| 归档时间: | 
 | 
| 查看次数: | 6013 次 | 
| 最近记录: |