Установить динамический цвет фона в React native - PullRequest
0 голосов
/ 05 июня 2018

Я создаю приложение погоды, в котором я хочу, чтобы цвет фона динамически изменялся в зависимости от погодных условий, выбранных из API OpenWeatherMaps.Тем не менее, я не совсем уверен, как это сделать, так как я получаю сообщение об ошибке, которое говорит: "Не определено не является объектом (рядом с '...}] цвет ...')

Прямо сейчас я предварительно определил условия в отдельном файле WeatherConditions и хочу, чтобы реквизиты в моем файле Weather определяли цвет фона. Как я могу это сделать?

Это мой метод рендеринга в файле Weather. Проблема заключается в первом теге просмотра после возврата:

 render() {
    const {
        weatherCondition,
        city,
        country,
        temperature,
        placeholder,
        weatherDescription,
        getWeather,
        handleTextChange,
        searchedCity
    } = this.props;
    const {
        weatherContainer,
        headerContainer,
        tempText,
        tempContainer,
        bodyContainer,
        inputContainer,
        textInputStyle,
        subtitle,
        title
    } = styles;

    return (
        <View
            style={[
                weatherContainer,
                {
                    backgroundColor:
                        weatherConditions[{ weatherCondition }].color
                }
            ]}
        >
            {" "}
            // Does not work right now.
            <View style={headerContainer}>
                <Text style={tempText}>
                    {" "}
                    {city} {country}
                </Text>
                <Text style={tempContainer}>
                    {" "}
                    {Math.round(temperature)}
                    ˚C
                </Text>
            </View>
            <View style={bodyContainer}>
                <View style={inputContainer}>
                    <TextInput
                        style={textInputStyle}
                        onChangeText={searchedCity =>
                            handleTextChange(searchedCity)
                        }
                        onSubmitEditing={() => getWeather()}
                        placeholder={placeholder}
                        clearTextOnFocus={true}
                        enablesReturnKeyAutomatically={true}
                    />
                </View>
                <Text style={title}>{weatherCondition}</Text>
                <Text style={subtitle}>{weatherDescription}</Text>
            </View>
            {this.renderLoading()}
        </View>
    );
}

Файл My WeatherCondition:

export const weatherConditions = {

Thunderstorm: {
color: '#303952'
},

Drizzle: {
color: '#8aacb8'
},

Rain: {
color: '#786fa6'
},

Snow: {
color: '#00d8d6'
},

Atmosphere: {
color: '#ff5252'
},

Clear: {
color: '#f5cd79'
},

Clouds: {
color: '#0be881'
},


}

1 Ответ

0 голосов
/ 05 июня 2018

Это должно быть

<View style={[weatherContainer, {
  backgroundColor: weatherConditions[weatherCondition].color
}]}>

Обратите внимание на синтаксис weatherConditions[weatherCondition].color, вам не нужны фигурные скобки.

weatherConditions - это объект, weatherCondition - переменная.Для доступа к свойству по имени переменной вы используете скобочные обозначения.

...