React Native Hooks - как использовать useStates в стилях

Я использую хуки, чтобы написать собственное приложение для реагирования. У меня проблема с использованием состояний внутри стилей. Фон текстового контейнера по умолчанию красный, а после нажатия кнопки «Подтвердить» он должен измениться на зеленый. На данный момент я сталкиваюсь с ошибкой, когда использую activeBtn в качестве backgroundColor в стиле. Пожалуйста, помогите мне изменить мой код правильным образом. Я упростил свой код, чтобы он был более понятным, как показано ниже:

import React, { useState } from "react";
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";

const DifficultScreen = (props) => {
  const [activeBtn, setActiveBtn] = useState("red");
  const confirmHandler = () => {
    setActiveBtn("green");
  };
  return (
    <View>
      <View style={styles.container}>
        <Text style={styles.title}>Difficult screen is showing</Text>
      </View>
      <View>
        <TouchableOpacity onPress={confirmHandler} style={styles.btn}>
          <Text>Confirm</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: activeBtn,
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    height: 90,
    padding: 35,
  },
  title: {
    color: "black",
    fontSize: 18,
  },
  btn: {
    color: "black",
    padding: "10%",
    backgroundColor: "white",
    borderRadius: "5px",
    alignSelf: "center",
    textAlign: "center",
    margin: "5%",
  },
});

export default DifficultScreen;

person Janet Pedram    schedule 20.04.2020    source источник


Ответы (5)


Что вы можете сделать, так это использовать его в стиле контейнера следующим образом:

измените это:

<View style={styles.container}>

to:

<View style={[styles.container, {backgroundColor: activeBtn}]}/>

Это способ добавить динамический стиль к компоненту.

person Jagrati    schedule 20.04.2020
comment
@JanetPedram подумайте о том, чтобы принять ответ, если он сработает. Спасибо. - person Jagrati; 24.04.2020

Свойство style поддерживает только один объект со свойствами стиля в нем, поэтому вам нужен способ объединить свойство внутри объекта стиля, на самом деле мы можем сделать это с помощью оператора распространения javascript или путем передачи свойств стиля в виде массива

измените это:

<View style={styles.container}>

to

<View style={{...styles.container, backgroundColor: activeBtn}}/>

or to :

<View style={[styles.container, {backgroundColor: activeBtn}]}/>
person Pradeepsinh Sindhav    schedule 27.10.2020

В вашем случае, когда только одно свойство CSS должно быть изменено внешним состоянием, я бы использовал решение, предоставленное Pradeepsinh Sindhav или Jagrati.

Если вам нужно передать несколько параметров, которые повлияют на многие свойства внутри таблицы стилей, вы можете получить объект styles, например, из функции getStyles:

import React, { useState } from "react";
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";

const DifficultScreen = (props) => {
  const [activeBtn, setActiveBtn] = useState("red");
  const [height, setHeight] = useState(90);
  const [padding, setPadding] = useState(20);

  const styles = getStyles(activeBtn, height, padding);

  const confirmHandler = () => {
    setActiveBtn("green");
    setHeight(120)
    setPadding(35)
  };

  return (
    <View>
      <View style={styles.container}>
        <Text style={styles.title}>Difficult screen is showing</Text>
      </View>
      <View>
        <TouchableOpacity onPress={confirmHandler} style={styles.btn}>
          <Text>Confirm</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const getStyles = (buttonColor, height, padding) => StyleSheet.create({
  container: {
    backgroundColor: buttonColor,
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    height: height,
    padding: padding,
  },
  title: {
    color: "black",
    fontSize: 18,
  },
  btn: {
    color: "black",
    padding: "10%",
    backgroundColor: "white",
    borderRadius: "5px",
    alignSelf: "center",
    textAlign: "center",
    margin: "5%",
  },
});

export default DifficultScreen;
person Oyzuu    schedule 12.01.2021

Я не уверен, что это нормально, и не получил предупреждения от реакции, но он отлично работает с моей темой. также вы можете использовать обработчики реакции, такие как useState, и добавить логику внутри этого настраиваемого крючка для стиля. Я использую useStyle вместо style.ts | js

import { StyleSheet } from 'react-native'
import { useTheme } from 'react-native-elements'
import { RFValue } from 'react-native-responsive-fontsize'


export const useStyle = () => {
  const { theme: { colors } }: any = useTheme()

  const styles = StyleSheet.create({
    container: {
      backgroundColor: colors?.text,
      height: RFValue(40),
      width: RFValue(40),
      justifyContent: 'center',
      alignItems: 'center',
      borderRadius: RFValue(4)
    },
  })

  return {
    styles,
    iconColor: colors.secondary,
    iconSize: RFValue(25)
  }
}
person Israel Calderon    schedule 25.03.2021

импортировать React, {useState} из «реагировать»; импортировать {StyleSheet, Text, View, TouchableOpacity} из "react-native";

const DifficultScreen = (props) => {
  const [activeBtn, setActiveBtn] = useState(styles.btnRed);
  const confirmHandler = () => {
    setActiveBtn(styles.btnGreen);
  };
  return (
    <View>
      <View style={styles.container}>
        <Text style={styles.title}>Difficult screen is showing</Text>
      </View>
      <View>
        <TouchableOpacity onPress={confirmHandler} style={activeBtn}>
          <Text>Confirm</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: activeBtn,
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    height: 90,
    padding: 35,
  },
  title: {
    color: "black",
    fontSize: 18,
  },
  btnRed: {
    color: "black",
    padding: "10%",
    backgroundColor: "white",
    borderRadius: "5px",
    alignSelf: "center",
    textAlign: "center",
    margin: "5%",
  },
  btnGreen: {
    color: "green",
    padding: "10%",
    backgroundColor: "white",
    borderRadius: "5px",
    alignSelf: "center",
    textAlign: "center",
    margin: "5%",
  },
});

export default DifficultScreen;
person EL173    schedule 20.04.2020
comment
Спасибо за ответ, но, к сожалению, этот метод у меня не работает. - person Janet Pedram; 20.04.2020