如何在StyleSheet中访问状态变量?

时间:2020-03-11 17:22:04

标签: reactjs react-native

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

但是我似乎无法在StyleSheet中访问它们,我只是收到一条错误消息,指出marginLeft未定义。

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

我如何访问变量?

1 个答案:

答案 0 :(得分:2)

我不确定要动态更改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"
  }
});

这不是最佳解决方案,但希望对您有所帮助。放心怀疑。