簡體   English   中英

在React中將狀態從子級傳遞到父級; 孩子有單獨的狀態

[英]Passing state from child to parent in React; child has separate state

我有三個組成部分,從最外層到最內層: App => Welcome => SearchBar AppSearchBar定義了一個狀態,但是我想要的是在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 prop為目標,以獲取輸入中的value

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

這可能會使重新渲染的次數最少。

編輯:

是的,提交表格后,我們可以完全顯示一個新組件。 我們只需要第二個狀態值(例如displayResultsdisplayComponent的幫助,然后通過使用簡單的if-check,就可以切換要顯示的組件。 請參見工作示例: 代碼演示

SearchBar組件中,您應該將state值直接傳遞給handleSubmit函數,例如,

<form onSubmit={(e)=>{e.preventDefault(); this.props.handleSubmit(this.state.value)}}>

App組件中, handleSubmit函數應為:

handleSubmit(inputValue) {
    this.setState({
      value: inputValue
    });
}

演示版

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM