在React中从父级更新类的道具

问题描述 投票:0回答:1

作为React的介绍,我正在重建Google Weather应用程序。我的目标是,当选择其中一天时,主要部分(以红色为边界)将更新。我以为我能够在App.js里面更新handleSelectionAt()里面的道具。任何帮助表示赞赏!

这是App.js

class App extends Component {
state = {
    city: 'Huntsville',
    state: 'AL',
    zip: '35801',
    currentDay: 'Saturday',
    currentHour: '12:00 PM',

    weathers: [//..weather info..//]
};

handleSelectionAt = indexToChange =>
    this.setState({
        weathers: this.state.weathers.map((weather, index) => {
            if (index === indexToChange) {

                // set location to update
                // Location.setProps(weather);

                return {
                    ...weather,
                    selected: true
                };
            } else {
                return {
                    ...weather,
                    selected: false
                }
            }
            return weather;
        })
    });

render() {
    return (
        <div className="App">
            <h1 align="center">React to the Weather</h1>

            <div className="Container">
                <Location
                    city={this.state.city}
                    state={this.state.state}
                    zip={this.state.zip}
                    weather={this.state.weathers[0]} />

                <WeatherList
                    weathers={this.state.weathers}
                    handleSelectionAt={this.handleSelectionAt} />
            </div>
        </div>
    );}}

这是我的位置类

const Location = props =>
<div className="Location">
    <h1>{props.city}, {props.state} {props.zip}</h1>
    <h2>{props.weather.day + 'day'} {props.currentHour}</h2>
    <h2>{props.weather.condition}</h2>
    <h3>
        <img
            id="currentCondition"
            align="center"
            src={require(`./img/${props.weather.condition.toLowerCase()}.png`)} alt='wtf'/>
        {Math.round((props.weather.high + props.weather.low)/2)}°</h3>
</div>

Location.propTypes = {
    city: PropTypes.string.isRequired,
    state: PropTypes.string.isRequired,
    zip: PropTypes.string.isRequired,
    currentHour: PropTypes.string.isRequired,   // Should update on each selection
    weather: PropTypes.object.isRequired,       // Should update on each selection
};
javascript html css reactjs
1个回答
1
投票

您总是在Location组件中传递第一个天气对象。

weather={this.state.weathers[0]}

在渲染方法中查找选定的天气并将其传递下来。

render() {
...
let selectedWeather= this.state.weathers.find(x=>x.selected);
<Location
...
    weather={selectedWeather}
/>
© www.soinside.com 2019 - 2024. All rights reserved.