TheMaxai
@TheMaxai

Как изменить стили при смене темы (Светлой, Темной)?

Я написал код. Работает исправно, но сам не могу оценить его правильность. э
Если в нем что-то не так подскажите пожалуйста.

App.js
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';


var currentTheme = "light"

var theme = {
	light: {
		backgroundColor: "white",
		colorText: "black",
	},
	dark: {
		backgroundColor: "black",
		colorText: "white",
	},
}


getStyles = () => {
	return StyleSheet.create({
	  container: {
	    flex: 1,
	    backgroundColor: theme[currentTheme].backgroundColor,
	    alignItems: 'center',
	    justifyContent: 'center',
	  },
	  text: {
	  	color: theme[currentTheme].colorText
	  }
  })
}


export default class App extends React.Component {
 constructor(props){
		super(props);
		this.state = {styles: getStyles()}
	}

	updateStyles() {
		this.setState({styles: getStyles()})
	}

	changeTheme() {
  	if (currentTheme == "light") {
  		currentTheme = "dark"
  	}
  	else {
  		currentTheme = "light"
  	}
  	this.updateStyles()
	}

  render() {
  	styles = this.state.styles
    return (
      <View style={styles.container}>
        <Text style={styles.text}>Open up App.js to start working on your app!</Text>
        <Text style={styles.text}>Changes you make will automatically reload.</Text>
        <Text style={styles.text}>Shake your phone to open the developer menu.</Text>
        <Button title="HELLO" onPress={() => this.changeTheme()}/>
      </View>
    );
  }
}
  • Вопрос задан
  • 103 просмотра
Решения вопроса 1
Zatmil
@Zatmil
Fullstack-разработчик
Ну, для начала, хотя бы так, чтобы избавиться от внешний переменных, которые только усложняют восприятие кода. Также можно сократить ненужные действия. А вообще лучше сделать оберточный компонент и через передачу значения темы менять стили внутри контекста, но это уже от задач зависит.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

getStyles = (currentTheme) => {
  const colors = {
    light: {
      backgroundColor: "white",
      colorText: "black",
    },
    dark: {
      backgroundColor: "black",
      colorText: "white",
    },
  };  
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors[currentTheme].backgroundColor,
      alignItems: 'center',
      justifyContent: 'center',
    },
    text: {
    	color: colors[currentTheme].colorText
    }
  })
};

export default class App extends React.Component {
  constructor(props){
    super(props);
    this.state = { currentTheme: 'light' }
  }
  changeTheme = () => {
  	this.setState(prevState => ({
      currentTheme: prevState.currentTheme === 'light' 
        ? 'dark'
        : 'light'
    }))
  }
  render() {
    const { currentTheme } = this.state;
    const styles = getStyles(currentTheme);
    return (
      <View style={styles.container}>
        <Text style={styles.text}>Open up App.js to start working on your app!</Text>
        <Text style={styles.text}>Changes you make will automatically reload.</Text>
        <Text style={styles.text}>Shake your phone to open the developer menu.</Text>
        <Button title="HELLO" onPress={this.changeTheme} />
      </View>
    );
  }
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы