【问题标题】:React Native - Scalable Stylesheet for Specified Screen SizesReact Native - 指定屏幕尺寸的可缩放样式表
【发布时间】:2021-11-26 12:31:24
【问题描述】:

我需要将样式大小更改为 3 种不同的大小,例如宽度

我尝试将条件样式表设为

{const width = useWindowDimensions().width;
 //Codes 
 ...}

if( 0 <= width <= 520) {
const styles = StyleSheet.create({
  container: {
    width: '%100',
  },
}
else if ( 521 <= width <= 768) {
const styles = StyleSheet.create({
  container: {
    width: '%70',
  },
}
else {
const styles = StyleSheet.create({
  container: {
    width: '%50',
  },
}

我怎样才能进行这样的操作?有没有更好的办法?

【问题讨论】:

    标签: react-native conditional-statements screen-size react-native-stylesheet


    【解决方案1】:

    我认为在这种情况下使用 StyleSheet 没有任何意义,因为它取决于运行时可用的变量(宽度),而使用 StyleSheet 不会获得任何性能优势了。我建议简单地创建一个函数,如:

    type getContainerWidth = (windowWidth: number) => number
    

    并将其直接传递给视图样式,例如:

    <View style={[styles.sharedContainerStyle, {width: getContainerWidth(windowWidth)}]} />
    

    【讨论】:

      【解决方案2】:

      您可以创建几种样式:

      w100: { width: '100%'}
      w70: { width: '70%'}
      w50: { width: '50%'}
      

      在 'return' 之前的 'render' 中(在类组件的情况下)使用 w100/w70/w50 创建 'const actualWidth' 并将其传递给 'style'。

      【讨论】:

        【解决方案3】:

        我就是这样弄的。

            import {useWindowDimensions,...} from 'react-native';
            const [styles, setStyles] = useState(stylesS);
        
            useEffect(() => {
                if (0 <= width && width < 768) {
                    // Small Screen
                    setStyles(stylesS);
                } else if (768 <= width && width < 992) {
                    //medium
                    setStyles(stylesM);
                } else {
                    //large
                    setStyles(stylesL);
                }
            }, [width]);
        
        const stylesS = StyleSheet.create({
        ...});
        
        
        const stylesM = StyleSheet.create({
        ...});
        
        
        const stylesL = StyleSheet.create({
        ...});
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-02
          • 2016-07-02
          • 2022-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多