【发布时间】:2019-04-02 11:52:14
【问题描述】:
我想我知道我需要做什么才能使我的searchLocationChange 功能正常工作,但我不确定该怎么做。请原谅缩进,在 StackOverflow 的 WYSIWYG 上有点挣扎!
这是我的父组件设置:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
forecasts: [],
location: {
city: '',
country: '',
},
selectedDate: 0,
searchText: '',
};
this.handleForecastSelect = this.handleForecastSelect.bind(this);
this.searchLocationChange = this.searchLocationChange.bind(this);
}
}
我想通过这个特定的功能来工作:
searchLocationChange() {
console.log(this.state.searchText);
Axios.get('https://mcr-codes-weather.herokuapp.com/forecast', {
params: {
city: this.state.searchText,
},
})
.then((response) => {
this.setState({
forecasts: response.data.forecasts,
location: {
city: response.data.location.city,
country: response.data.location.country,
}
});
});
}
而在我的 Child 组件中,逻辑是:
class SearchForm extends React.Component {
constructor(props) {
super(props);
this.state = {
searchText: '',
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const enteredText = event.target.value;
this.setState({
searchText: enteredText
});
}
render() {
return (
<span className="search-form">
<div className="search-form__input"><input type="text" value={this.state.searchText} onChange={this.handleInputChange} /></div>
<div className="search-form__submit"><button onClick={this.props.searchLocationChange}>Search</button></div>
</span>
);
}
}
我意识到我正在尝试使用来自子组件状态的 searchText 更新父组件,但我无法弄清楚我需要更改哪些内容才能使其正常工作。我有一个偷偷摸摸的怀疑,我已经完成了 99% 的路,而且我只需要多几行,但我可能会走得很远?
【问题讨论】:
标签: reactjs components state