【发布时间】: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