2017-12-05 23 views
0

子コンポーネントを通って入ってくるデータに基づいて親コンポーネントの状態を変更しようとしています。私はボタンなしで親を変更する方法を理解できません。子要素のthis.state.rowsがデータベースから来て、データがロードされている間に回転アイコンを表示できるように状態を変更したいと思います。子コンポーネントの状態を、子コンポーネントのデータのレンダリングに基づいて変更しようとしています。

class Parent extends Component{ 
    constructor(props){ 
    super(); 
    this.state={ 
     spinner=false 
    } 
    this.spinnerUpdate = this.spinnerUpdate.bind(this) 
    } 

    spinnerUpdate(){} 

    render(){ 
    return(
     <Child spinner={this.spinnerUpdate}/> 
    ) 
    } 
} 


class Child extends Component{ 
    constructor(props){ 
    super(props); 
    this.state={ 
     rows: rows, 
    } 
    this.spinner = this.spinner.bind(this) 
    } 

    spinner(){ 
    if(this.state.rows){ 
     this.setState({spinner: true}) 
    } 
    } 

    render(){ 
    return(
     <div> 
     //random info 
     </div> 
    ) 
    } 
} 

私は、データがレンダリングされるとき、親状態の状態を変更するには、子コンポーネントでスピナー機能を期待しました。

+0

このコードはコンパイルされません 'this.state =を{ スピナー=偽 }' –

+0

spinnerUpdateはまた、私はこれを試みNOOP機能.... –

答えて

0

子コンポーネントは、親コンポーネントから渡された小道でspinnerを受け取ります。

class Parent extends Component{ 
     constructor(props){ 
     ... 
      this.spinnerUpdate = this.spinnerUpdate.bind(this) 
     } 

     //will receive one param from Child component to hide/show spinner. 
     spinnerUpdate(spinnerStatus){ 
      this.setState({spinner: spinnerStatus}) 
     } 

     render(){ 
      return(
      <Child spinner={this.spinnerUpdate}/> 
     ) 
     } 
     } 


     class Child extends Component{ 
     constructor(props){ 
      ... 
     } 

     spinner(){ 

    //call spinner of parent based on matched criteria 
      if(this.state.rows){ 
      this.props.spinner(true); 
      }else{ 
      this.props.spinner(false); 
      } 
     } 

     render(){ 
      return(
      <div> 
       //random info 
      </div> 
     ) 
     } 
     } 
+0

であり、それは動作しませんでした。小道具で関数spinner()を宣言する必要がありますか? – yabna

+0

それはwork.howスピナーを呼び出す必要がありますか? –

関連する問題