【发布时间】:2019-01-24 10:39:43
【问题描述】:
我最近开始使用 React,想构建一个小应用程序来获取天气数据。我的 API 具有返回自动完成建议的功能。因此,当我的自动建议数组不为空时,我会呈现一个列表,然后单击其中一个 <li>'s 我想要输入框中的值。我设法设置了SearchBar 的状态,但无法更改它的值。
编辑:我尝试将我的值从changeState() 获取到我的<input type="text" placeholder="City, Zip Code, Coordinates" onChange={evt => this.updateInputValue(evt)} />。我可以搜索其他术语。
import React from 'react';
import './SearchBar.css';
import Suggestion from './Suggestion';
class SearchBar extends React.Component{
constructor(props) {
super(props);
this.state = {inputValue: ''};
this.search = this.search.bind(this);
this.updateInputValue = this.updateInputValue.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
this.changeState = this.changeState.bind(this);
}
changeState(value) {
console.log(value);
// Logs value of text between <li></li>
this.setState({inputValue: value});
}
search() {
this.props.onSearch(this.state.inputValue);
}
updateInputValue(evt) {
this.setState({
inputValue: evt.target.value
});
this.props.onChange(this.state.inputValue);
}
handleKeyPress(e) {
if(e.key === 'Enter') {
this.search();
}
}
render() {
return (
<div>
<div className="SearchGroup" onKeyPress={this.handleKeyPress} >
<input type="text" placeholder="City, Zip Code, Coordinates" onChange={evt => this.updateInputValue(evt)} />
<a onClick={this.search}>Go</a>
</div>
<Suggestion autocomplete={this.props.autocomplete} onSelect={this.changeState} />
</div>
);
}
}
export default SearchBar;
为了完整起见我的Suggestion.js:
import React from 'react';
import './Suggestion.css';
class Suggestion extends React.Component{
constructor(props) {
super(props);
this.updateInputField = this.updateInputField.bind(this);
}
updateInputField(evt) {
this.props.onSelect(evt.currentTarget.innerText);
}
render(){
if(this.props.autocomplete && this.props.autocomplete.length > 0) {
return (
<div className="Suggestion">
<ul>
{
this.props.autocomplete.map((location) => {
return (
<li key={location.id} onClick={this.updateInputField}>{location.name}</li>
)
})
}
</ul>
</div>
);
} else {
return <div className="None"></div>
}
}
}
export default Suggestion;
我还希望在Suggestion 中提交location.url,但我找不到与evt 内部匹配的属性。
【问题讨论】:
-
也许你应该试试
{this.changeState(e)}} /> -
@Mehmetnuri 这会有什么不同? OP 已经明确绑定 this。
-
这应该是 updateInputValue(evt) { this.setState({ inputValue: evt.target.value }); this.props.onChange(evt.target.value); // 这里如果你传递状态值你不会得到更新的值,它只有在渲染后才会更新,所以你需要将 evt.target.value 直接传递给 onChange }
标签: javascript reactjs