通常,在Component外部声明StyleSheet.create。但是,我已经在render()中添加了StyleSheet.create,以利用某些页面上的redux state。
每次你reRender的时候,你都会调用StyleSheet.create,这有问题吗?
import React, { Component } from 'react';
import { Text, View, StyleSheet,Button } from 'react-native';
import { Constants } from 'expo';
import TestView from './TestView';
const styles = StyleSheet.create({
text:{
fontSize:14,
}
})
const useStateStyles = fontSize => StyleSheet.create({
text:{
fontSize:fontSize,
}
})
export default class App extends Component {
state = {
fontSize:14,
}
render() {
const { fontSize } = this.state;
this.styles = useStateStyles(fontSize);
return (
<View style={{flex:1,marginTop:20}}>
<Button
title="+"
onPress={()=>{this.setState({
fontSize:fontSize+2
})}}
/>
<Button
title="-"
onPress={()=>{this.setState({
fontSize:fontSize-2
})}}
/>
<Text style={styles.text}>{fontSize}</Text>
<Text style={this.styles.text}>{fontSize}</Text>
</View>
);
}
}如果StyleSheet.create是外部的和固定的,那么当State改变时,它不能被改变。所以在render中调用useStateStyles。
发布于 2019-08-07 10:20:38
您不必多次调用style代码。您可以使用state value
您可以直接在style中声明status value。
import React, { Component } from 'react';
import { Text, View, StyleSheet,Button } from 'react-native';
import { Constants } from 'expo';
export default class App extends Component {
constructor(props){
super(props);
this.state = {
fontSize:14,
}
}
render() {
const { fontSize } = this.state;
return (
<View style={{flex:1,marginTop:20}}>
<Button
title="+"
onPress={()=>{this.setState({
fontSize:fontSize+2
})}}
/>
<Button
title="-"
onPress={()=>{this.setState({
fontSize:fontSize-2
})}}
/>
<Text style={{fontSize: this.state.fontSize}}>Test text</Text>
</View>
);
}
}https://stackoverflow.com/questions/57385885
复制相似问题