【问题标题】:What is the best way to manage styles that depend on props? [closed]管理依赖于道具的样式的最佳方法是什么? [关闭]
【发布时间】:2020-09-09 01:44:37
【问题描述】:

我有一个这样的基本组件:

const BasicComponent = (props) => {
    return <Text style={styles.text}>Hi!</Text>
}

const styles = StyleSheet.create({
    text: {
        fontSize: 20
    }
})

我希望能够采用改变文本颜色的道具。我可以将返回更改为

<Text style={[styles.text, {color: props.color}]}>Hi!</Text>

或将const styles 移动到BasicComponent 函数中并在那里设置color: props.color,在我看来这看起来更干净。

我以前从未在函数/类中看到const styles。但它工作得很好。一种方法优于另一种方法吗?哪个是最佳实践?还是看个人意见?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    这在处理多个主题时很有帮助,我通常做的是使用样式表的函数,如下所示:

    import React, { useState } from 'react';
    import { Text, Button, View, StyleSheet } from 'react-native';
    
    const Demo = ({ theme = 'light', toggleTheme }) => (
      <View style={styles.container(theme)}>
        <Text style={styles.title(theme)}>{theme}</Text>
        <Button title="Change Theme" onPress={toggleTheme} />
      </View>
    );
    
    export default () => {
      const [theme, setTheme] = useState('light');
    
      const toggleTheme = () => setTheme(theme === 'light' ? 'dark' : 'light');
    
      return <Demo theme={theme} toggleTheme={toggleTheme} />;
    };
    
    const styles = StyleSheet.create({
      container: theme => ({
        flex: 1,
        justifyContent: 'space-around',
        alignItems: 'center',
        backgroundColor: theme === 'light' ? '#fff' : '#000',
      }),
      title: theme => ({
        fontSize: 25,
        color: theme === 'light' ? '#000' : '#fff',
      }),
    });
    
    

    在这里查看工作零食https://snack.expo.io/@abranhe/61e11d

    【讨论】:

      【解决方案2】:

      我有个类似的想法希望对你有帮助

      const BasicComponent = (props) => {
          const {color} = props
          return <Text style={styles.text(color)}>Hi!</Text>
      }
      
      const styles = StyleSheet.create({
          text: (color = "black") => ({
              fontSize: 20,
              color: color
          })
      })
      
      

      【讨论】:

      • 这个答案可以通过解释来改进。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 2012-01-27
      • 2010-11-16
      相关资源
      最近更新 更多