首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多次调用StyleSheet.create会影响性能吗?

多次调用StyleSheet.create会影响性能吗?
EN

Stack Overflow用户
提问于 2019-08-07 09:33:31
回答 1查看 113关注 0票数 0

通常,在Component外部声明StyleSheet.create。但是,我已经在render()中添加了StyleSheet.create,以利用某些页面上的redux state

每次你reRender的时候,你都会调用StyleSheet.create,这有问题吗?

代码语言:javascript
复制
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

https://snack.expo.io/SJOMaiwXH

EN

回答 1

Stack Overflow用户

发布于 2019-08-07 10:20:38

您不必多次调用style代码。您可以使用state value

您可以直接在style中声明status value

代码语言:javascript
复制
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>
    );
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57385885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档