2016-09-05 4 views
0

私はこのコードで間違っているとわかりません、プロンプトの値はフロントエンドでは更新されませんそれは価値が増加する。Windowで子小道具の値は更新されていませんが、コンソールで更新されていることがわかります

import React from 'react'; 
    import { render } from 'react-dom'; 


    class Parent extends React.Component{ 
     constructor(props){ 
      super(props); 
      this.number=0; 
      this.changeValue=this.changeValue.bind(this); 
     } 

     changeValue(){ 
      console.log('-------------this.number',this.number); 
      this.number=this.number+1; 
     } 

     render(){ 
      return(
       <div> 
        <Child callMe={this.changeValue} increaseNo={this.number}></Child> 
       </div> 
      ) 
     } 
    } 


    class Child extends React.Component{ 

     render(){ 
      return(
       <div> 
        <button onClick={this.props.callMe}>CLick Me</button> 
        <h1>{this.props.increaseNo}</h1> 
       </div> 
      ) 
     } 
    } 

    render(<Parent/> , document.getElementById('root')); 

答えて

1

あなたはコンポーネントstatethis.numberを格納する必要があり、構成要素は、そのstate変更された場合のみ再レンダリングされるか、新しいpropsを受け取ります。

class Parent extends React.Component{ 
    constructor(props){ 
     super(props); 
     this.state = { 
      number: 0 
     } 
     this.changeValue=this.changeValue.bind(this); 
    } 

    changeValue(){ 
     this.setState({number: this.state.number + 1}); 
    } 

    render(){ 
     return(
      <div> 
       <Child callMe={this.changeValue} increaseNo={this.state.number}></Child> 
      </div> 
     ) 
    } 
} 


class Child extends React.Component{ 

    render(){ 
     return(
      <div> 
       <button onClick={this.props.callMe}>CLick Me</button> 
       <h1>{this.props.increaseNo}</h1> 
      </div> 
     ) 
    } 
} 

jsfiddle

+0

感謝。はい、このソリューションは機能しますが、なぜthis.numberは機能しませんでしたか?それはReactがstateが更新されているときだけdomを描画するからです。私が間違っていれば私を訂正してください。 –

+0

**コンポーネント**の状態が更新されるか、新しい小道具を受け取ると、 'this.number'は州の一部でもないし、親が再レンダリングしないような小道具でもありません。ここでコンポーネントのライフサイクルについて読むことができます。http://stackoverflow.com/documentation/reactjs/2750/react-component-lifecycle#t=201609051001078991495 – QoP

関連する問題