reactjs - 在 React 中将状态从子级传递给父级;孩子有单独的状态
问题描述
我有三个组件,从最外层到最里面:App
=> Welcome
=> SearchBar
。在App
and中定义了一个状态SearchBar
,但我想要的是在 SearchBar 中获取用户输入的数据并将其显示在“结果”页面中。因此,我正在尝试更新状态SearchBar
并同时更新状态App
,以便我可以将该数据传递给另一个组件,该组件是App
(例如Results
)的子组件。我有以下代码,但它只更新状态, SearchBar
而不是更新App
.
(我看过一些孩子(在这种情况下SearchBar
)没有自己的状态的例子,但在这种情况下,我认为这是必要的,因为我正在跟踪用户输入。不过我可能错了。)
// App.js
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.setState({
value: event.target.value
});
}
render() {
return (
<Router>
<div className="AppContainer">
<Route
exact
path="/"
render={props => <SearchBar handleSubmit={this.handleSubmit} />}
/>
...
// Welcome.js
export default class Welcome extends React.Component {
render() {
return (
<div>
<SearchBar handleSubmit={this.props.handleSubmit} />
</div>
...
// SearchBar.js
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
event.preventDefault();
this.setState({ value: event.target.value });
}
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<input
type="text"
placeholder="Search..."
onChange={this.handleChange}
value={this.state.value}
/>
<input type="submit" />
</form>
);
}
}
再说一次,我对 React 很陌生,所以这可能不是你应该使用的模式。无论如何,我会很感激关于如何最好地解决这个问题的建议。
解决方案
由于您已经在其中定义了一个handleSubmit()
事件处理程序App.js
并将其一直传递给您的SearchBar.js
组件。您可以通过在 SearchBar 中为输入标签提供名称道具来推断所需的数据。
class Searchbar extends React.Component {
state = {
value: ""
};
handleOnChange = e => {
this.setState({
value: e.target.value
});
};
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<input
onChange={this.handleOnChange}
value={this.state.value}
name="search"
/>
</form>
);
}
}
然后在App.js
handleSubmit 处理程序中,以该name
道具为目标以获取value
输入。
handleSubmit = e => {
e.preventDefault();
this.setState({
value: e.target.search.value
})
};
这可能会有最少的重新渲染。
编辑:
是的,我们可以在提交表单时完全显示一个新组件。我们只需要第二个状态值的帮助,displayResults
或者displayComponent
然后通过使用简单的 if-check,我们只需切换要显示的组件。请参阅工作示例:代码演示
推荐阅读
- elasticsearch - 弹性搜索查询返回每个类别的前 3 个
- c# - 将日志目标写入 EventStore
- php - 如何在 nginx-bitnami-CI 中设置子目录?
- javascript - 如何使用 sequelize 或 sql 从不同的表聚合总和?
- python - 在 H2O 框架中查找小时
- devops - 从 Rundeck 触发 control-m 中的作业
- c# - Handlebars.Net 如果比较助手未检测到参数类型
- java - liquibase 中的动态占位符配置生成动态校验和
- arrays - 如何按时间戳对值进行分组
- javascript - 无法在 vue cli 3 中运行命令 ~$ vue add unit-mocha