子类Search
的格式输入需要搜索一些字符串(例如:城市中的某些区域)。父组件App
以状态存储搜索的值,以将其作为道具传递给另一种方法(Map
组件)。
问题:当我开始在搜索表单中输入内容时,searchedValue
会立即在父级中更新(由于onSearchedInputChange
方法而无法使用)-
在更新父级状态之前,我如何让表单等到单击Enter
之前?
App.js(父级)
class App extends React.Component {
state = {
searchedValue: "",
searchedResponse: null
};
handleSubmit = e => {
e.preventDefault();
...
};
onSearchedInputChange = searchedValue => {
this.setState({
searchedValue: searchedValue
});
};
Search.js(子级)
class Search extends Component {
handleSubmit = e => {
this.props.handleSubmit(e);
};
// pass callback to parent with searched field
handleSearch = e => {
if (e.key === "Enter") {
this.props.onSearchedInputChange(e.target.value);
}
};
render() {
const searchedValue = this.props.searchedValue;
return (
<div className="search">
<Form onSubmit={this.handleSubmit}>
<Form.Group controlId="searchForm" className="search-form">
<InputGroup>
<InputGroup.Prepend>
<FontAwesomeIcon icon={faSearch} className="search-icon" />
</InputGroup.Prepend>
<Form.Control
className="search-input"
type="text"
placeholder="Enter street or area..."
value={searchedValue}
name="search"
onChange={this.handleSearch}
/>
</InputGroup>
</Form.Group>
</Form>
</div>
);
}
}
答案 0 :(得分:1)
首先,您应该将输入值保存在子状态中,然后传递它,该句柄键事件以检查是否单击enter后,通过两种方式将子状态searchTerm
传递到父类。因此,键入完毕后,文本将以searchTerm
的状态保存,当您单击Enter并从prop调用函数并将searchTerm
传递给父类时。
这是代码:
class Search extends Component {
state = {
searchTerm: ""
};
handleSubmit = e => {
this.props.handleSubmit(e);
};
handleSearch = e => {
this.setState({ searchTerm: e.target.value });
};
handleKeyPress = e => {
if (e.key === "Enter") {
this.props.onSearchedInputChange(this.state.searchTerm);
}
};
render() {
return (
<div className="search">
<Form onSubmit={this.handleSubmit}>
<Form.Group controlId="searchForm" className="search-form">
<InputGroup>
<InputGroup.Prepend>
<FontAwesomeIcon icon={faSearch} className="search-icon" />
</InputGroup.Prepend>
<Form.Control
className="search-input"
type="text"
placeholder="Enter street or area..."
value={this.state.searchTerm}
name="search"
onChange={this.handleSearch}
onKeyPress={this.handleKeyPress.bind(this)}
/>
</InputGroup>
</Form.Group>
</Form>
</div>
);
}
}