簡體   English   中英

如何在React中訪問父組件狀態

[英]How to access a parent components state in react

我想訪問父組件SubmitForm的狀態,並通過返回帶有查詢結果的span元素來返回結果。

偽造的DB或JSON文件為:

const citi = [
  {
    pc: '13000',
    city: 'berlin',
    population: '10million'
  }, {
    pc: '81000',
    city: 'munich'
  }
];

這些是更改和提交事件處理程序:

handleChange(event) {

  this.setState({ value: event.target.value });
}

handleSubmit(event) {
  alert('We will find the city for postal code: ' + this.state.value);
  event.preventDefault();
  var result = citi.filter(obj => obj.pc === this.state.value)[0].city;
  console.log(result);
  this.setState({ value: result });
}

和渲染方法

render() {
  return (

    <form onSubmit={this.handleSubmit}>
      <label>
        Search by postcode:
     <input type="text" value={this.state.value} onChange={this.handleChange}
        />
      </label>
      <button type="submit" className="btn btn-default">Search</button>
      <ComponentB />
    </form>
  );
}

這是子組件

class ComponentB extends React.Component {
  constructor(props) {
    super(props);
    // this.state = {val: 'hdgfh'};

  }


  render() {
    return <span>The postcode is in : {this.props.value}</span>;
  }
}

當我在父級組件中全部渲染時,一切正常,但是如何在父級中渲染並顯示結果? 控制台會記錄正確的結果,但是有關訪問父/子狀態的所有問題對我來說都沒有幫助。

Codepen鏈接:

https://codepen.io/damPop/pen/ReXwoo?editors=0010

您將需要通過props傳遞value它們不會被繼承

所以

<ComponentB value={this.state.value} />

更新的筆: https : //codepen.io/anon/pen/jQNvOe?editors=0010

您應該將父母的狀態作為道具傳遞,如下所示:

<ComponentB value={this.state.value}/>

暫無
暫無

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

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