【问题标题】:What is the best way to dynamically scale styles in React Native Web on window resize?在 React Native Web 中调整窗口大小时动态缩放样式的最佳方法是什么?
【发布时间】:2021-01-16 20:20:38
【问题描述】:

我正在尝试创建一个响应式 React Native Web 应用程序,它也支持 iOS 和 Android。

我发现似乎没有办法根据不断变化的窗口大小动态调整大小。

我想在调整窗口大小时调整一些卡片的大小。

这是我的风格:

MainStyles = StyleSheet.create(
    {
        card: {
            alignItems: 'center',
            justifyContent: 'space-between',
            alignSelf: "flex-end",
            marginBottom: scale(10),
            marginLeft: scale(10),
            marginRight: scale(10),
            shadowColor: colorBlack,
            shadowOffset: {
                width: 4,
                height: 4,
            },
            shadowOpacity: 0.53,
            shadowRadius: scale(3.62),
            elevation: 4,
            alignSelf: "flex-end", 
        }
    }

但是,如果我尝试添加这样的内容:

const window = Dimensions.get("window");

const width_proportion = (window.width * .20);
const height_proportion = (window.height * .20);

它只是在样式表中设置一个静态值,不会更新。

我必须在我的组件中实际执行此操作,感觉有点过于耦合:

class Card extends Component {
    constructor(props) {
        super(props);
        this.state = {
            cardSize: (Dimensions.get("window").width * .2)
        }
    }

componentDidMount() {
    if(window.addEventListener) {
        window.addEventListener('resize', this.resize)
        }
}

resize = () => {
    // Going for a square size, hence using width for both height/width.
    const window = Dimensions.get("window");
    this.setState({cardSize: (window.width * .2)})
     this.forceUpdate()
   }

render() {
return(
<View style={[MainStyles.card, { width: this.state.cardSize, height: this.state.cardSize}]}>
...
</View>
     );
   }
}

有没有一种更简洁的方法可以让我向 React Native Web 添加动态样式,而无需直接在组件中生成样式?我想要的只是让我的样式在窗口大小调整时动态更新。

【问题讨论】:

    标签: javascript css react-native react-native-web


    【解决方案1】:

    拥有我们自己的代码库总是好的,但如果您正在寻找简单的解决方案,那么您可以试试这个插件

    https://www.npmjs.com/package/react-native-responsive-screen
    

    他们提供了一些很酷的功能,或者也有多个插件可用。

    编码愉快!!!

    【讨论】:

    • 这里最大的烦恼是它是每个组件。我想要一个通用的调整大小,就像常规的 Web 开发一样。
    【解决方案2】:

    我认为最好只使用 flex: 使用 Flexbox 文档进行布局https://reactnative.dev/docs/flexbox

    通过这种方式,您可以创建带有填充的视图。它会自动调整大小。

    <View style={{flex: 1, padding: 15}} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-02
      • 2011-07-09
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多