简体   繁体   中英

pass state value from one component to another component's Api.create value

I am new to React.js here. I want to pass selectedMonth state value (from Header.js) to Api create function in (App.js). There is a dropdown in the Header.js. The selectedMonth will be calculated using dropdown value. In the App.js, need to filter my data in Api.create(). Not sure how to add it using props.Can anyone help on this?

Header.js

class Header extends Component {

constructor(props) {
super(props);
this.state = {
  value: ''
  selectedMonth: formatMonth(defaultMonth)
};

this.onChange = this.onChange.bind(this);

}
onChange(event) {
this.setState({selectedMonth: formatMonth(event.value) });

}
render() {

return (

  <header className="header">
      
      <Dropdown className="dropdown-month" value={this.state.value}/>     '''this is the dropdown for month and the selectedMonth will be calculated from the dropdown value'''
    </div>    
  </header>
);
 }
}

export default Header;

App.js

class App extends Component {
 constructor(props) {
  super(props);

  this.state = {
     isLoading: false,
  };

 }

  getWOT() {
    Api.create().getWOT().then(res => {    '''want to add selectedMonth here'''
     if (res.ok) {
        if (res.data) {
           const data = res.data.Result;
        }
        else {
           window.alert(res.problem)
        }
     }
  })
 }
 render() {

  const renderusers = _.map(this.state.allWOT, (value) => (
   
        <div className="line-bars">
           <div className="bar-title">Total Reject</div>
           <div className="container">
              
           </div>
        </div>

     

  ));



  return (


     this.state.isLoading ?
        <h3 style={{ textAlign: 'center' }}>loading...</h3>
        :

        <div>
           <Header />

           <div className="grid-container">
              <div className="main-grid">
                 
              </div>

              {renderusers}

           </div>


        </div>
  );
   }
 }
 export default App;

I had moved the value and selectedMonth state to App. js.

class App extends Component {
constructor(props) {
  super(props);

  this.state = {
     isLoading: false,
     allWOT: [],
     value: defaultMonth,
     selectedMonth: formatMonth(defaultMonth),
   };
   this.onChange = this.onChange.bind(this);

 }

  onChange(event) {
  this.setState({ value: event.value, selectedMonth: formatMonth(event.value) });
}

Then, return

<Header value={this.state.value} onChange={this.onChange}/>

And in Header.js just return Dropdown with value and onChange of this.props

 <Dropdown className="dropdown-month" options={months} value={this.props.value} onChange={this.props.onChange} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM