首页 > 解决方案 > 在 React 中将状态从子级传递给父级;孩子有单独的状态

问题描述

我有三个组件,从最外层到最里面:App=> Welcome=> SearchBar。在Appand中定义了一个状态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 很陌生,所以这可能不是你应该使用的模式。无论如何,我会很感激关于如何最好地解决这个问题的建议。

标签: reactjsreact-router

解决方案


由于您已经在其中定义了一个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.jshandleSubmit 处理程序中,以该name道具为目标以获取value输入。

  handleSubmit = e => {
    e.preventDefault();
    this.setState({
       value: e.target.search.value
    })
  };

这可能会有最少的重新渲染。

编辑:

是的,我们可以在提交表单时完全显示一个新组件。我们只需要第二个状态值的帮助,displayResults或者displayComponent然后通过使用简单的 if-check,我们只需切换要显示的组件。请参阅工作示例:代码演示


推荐阅读