如何在react原生样式表中正确使用条件样式

92dk7w1h  于 2021-10-10  发布在  React
关注(0)|答案(2)|浏览(142)

我有绿色,蓝色和红色的按钮主题。我的解决方案是可行的,但看起来很混乱。如果参数不是,我如何像在对象中那样使用它们呢?

const buttonBG = theme === 'green' ? COLORS.green : theme === "blue" ? COLORS.blue : ""

 const fontTheme = theme === 'green' ? FONTS.green : theme === "blue" ? FONTS.blue : ""

    const styles = StyleSheet.create({
        button: {
            backgroundColor: buttonBG,
            borderRadius: 12,
            paddingVertical: 16,
            paddingHorizontal: 20,
            lineHeight: 24,
            font: fontTheme 
        },
0ejtzxu1

0ejtzxu11#

我想您可以在<ThemedBtn/>内部选择主题的颜色,也许在组件外部这样做会使<ThemedBtn/>内部的代码看起来更干净?

应用程序组件

import React, {useState} from 'react';
import {View} from 'react-native';

import ThemedBtn from './components/ThemedBtn';

const _COLORS = {
  blue: 'blue',
  red: 'red',
  green: 'green',
};

const _FONT_COLORS = {
  blue: 'blue',
  red: 'red',
  green: 'green',
};

const App = () => {
  // edit start -> My best guess how you would like to alter the theme
  const [bgColor, setBgColor] = useState(_COLORS.blue);
  const [fontTheme, setFontTheme] = useState(_FONT_COLORS.red);
  // edit end ->

  return (
    <View>
      <ThemedBtn bgColor={bgColor} fontTheme={fontTheme} />
    </View>
  );
};

export default App;

主题按钮组件

export default function ThemedBtn({btnBg, fontTheme}) {
  const {btnStyles} = useMemo(
    () =>
      StyleSheet.create({
        btnStyles: {
          backgroundColor: btnBg,
          borderRadius: 12,
          paddingVertical: 16,
          paddingHorizontal: 20,
          lineHeight: 24,
          font: fontTheme,
        },
      }),
    [btnBg, fontTheme],
  );

  return (
    <TouchableOpacity style={btnStyles} title="Press Me">
      <Text style={{color: btnStyles.font}}>Press Me</Text>
    </TouchableOpacity>
  );
}
bmp9r5qi

bmp9r5qi2#

在样式中传递值的一种更简洁的方法如下

import { StyleSheet, Text, View } from 'react-native'
import React from 'react'

const App = () => {
  return (
    <Button 
        style={styles.btn('red')}
    />
  )
}

export default App

const styles = StyleSheet.create({
    btn : (color) => ({
        color : color
    })
})

相关问题