Javascript 在React中从父级更新类的道具
作为回应的介绍,我正在重建谷歌天气应用程序。我的目标是,当选择其中一天时,红色边框的主要部分将更新。我想我可以在App.js中更新HandleSelection中的道具。感谢您的帮助 下面是App.jsJavascript 在React中从父级更新类的道具,javascript,html,css,reactjs,Javascript,Html,Css,Reactjs,作为回应的介绍,我正在重建谷歌天气应用程序。我的目标是,当选择其中一天时,红色边框的主要部分将更新。我想我可以在App.js中更新HandleSelection中的道具。感谢您的帮助 下面是App.js class App extends Component { state = { city: 'Huntsville', state: 'AL', zip: '35801', currentDay: 'Saturday', currentHour: '12:
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
};
始终通过位置组件中的第一个天气对象
weather={this.state.weathers[0]}
在渲染方法中找到选定的天气并向下传递
render() {
...
let selectedWeather= this.state.weathers.find(x=>x.selected);
<Location
...
weather={selectedWeather}
/>
非常感谢。出于某种原因,我认为render更像是一个构造函数。