【问题标题】:How can i access my state variables in StyleSheet?如何在 StyleSheet 中访问我的状态变量?
【发布时间】:2020-03-11 17:22:04
【问题描述】:

我根据我在应用程序中显示的图像计算各种边距,每次选择图像时,它们的像素宽度范围都不同,所以我需要我们非常动态。计算完边距宽度后,我将它们保存在状态变量 marginL 和 marginR 中。

但是我似乎无法在 StyleSheet 中访问这些,我只是收到一条错误消息,说 marginLeft 未定义。

const styles = StyleSheet.create({
    container: {
      flex: 1, 
    },
    gap: {
      flex: 0.5,
      marginLeft: this.state.marginL,
      marginRight: this.state.marginR
    }
})

如何访问我的变量?

【问题讨论】:

  • 此代码示例是否在有状态组件中?如果是这样,您能否包含更多组件,尤其是(初始)状态是如何设置的以及该对象是何时创建的?

标签: reactjs react-native


【解决方案1】:

我不确定StyleSheet 值的动态变化。但是当您计算边距宽度时,您可以覆盖您的样式,如下所示

<View style={[styles.gap, {marginLeft: this.state.marginL, marginRight: this.state.marginR}]} />

查看完整示例

import React, { Component } from "react";
import { View, StyleSheet } from "react-native";

export default class App extends Component {
  state = {
    marginL: 10,
    marginR: 20
  };

  render() {
    return (
      <View style={styles.container}>
        <View style={[ styles.gap, { marginLeft: this.state.marginL, marginRight: this.state.marginR }]} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "red"
  },
  gap: {
    flex: 0.5,
    marginLeft: 0,
    marginRight: 0,
    backgroundColor: "green"
  }
});

这不是最佳解决方案,但希望对您有所帮助。欢迎提出疑问。

【讨论】:

  • 嗨,这是迄今为止我发现的唯一可行的解​​决方案(我目前正在使用它),但感觉不如 StyleSheet 本身中的值那么简洁。这就像变量分布在 2 个区域(在 Render 和 StyleSheet 中)。谢谢
  • @chai86 正如我提到的,这可能不是最佳解决方案
猜你喜欢
  • 2020-12-20
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 2020-09-09
相关资源
最近更新 更多