我根据我在应用程序中显示的图像计算各种边距,每次选择图像时,这些边距的范围都在不同的像素宽度内,因此我需要我们保持动态。一旦计算出边距宽度,就将它们保存在状态变量marginL和marginR中。
但是我似乎无法在StyleSheet中访问它们,我只是收到一条错误消息,说marginLeft是未定义的。
const styles = StyleSheet.create({
container: {
flex: 1,
},
gap: {
flex: 0.5,
marginLeft: this.state.marginL,
marginRight: this.state.marginR
}
})
如何获取变量?
我不确定要动态改变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"
}
});
这不是最佳解决方案,但希望对您有所帮助。如有疑问,请放心。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句