2017-07-27 43 views
2

我有一個多級層次結構類A-> B->類C,通過它我必須傳遞數字。React中的類型檢測

的父類是像這個 -

import propTypes from 'prop-types'; 
     class App extends React.Component{ 
      constructor(props){ 
       super(props); 
       this.state={ 
        text:0, 
        isClicked:false 
      } 
      this.display=this.display.bind(this); 
     } 
     display(){ 
     var num=document.getElementById('number').value; 
     var text=parseInt(num); 
     this.setState({ 
      isClicked:true, 
      text:text 
     }) 

     } 
     render(){ 
     return(
     <div className="row"> 
       <div className="col-md-6"> 
        <input type="text" placeholder="Enter name" value={this.state.label}/> 
        <input type="text" type='number' id='number'/> 
        <button onClick={this.display}>Click here</button> 
       </div> 
       <div className="col-md-6"> 
        <Display click={this.state.isClicked} data={this.state.text}/> 
       </div> 
       </div> 

      ) 
      } 
     } 
     App.propTypes={ 
      text:propTypes.number, 
      num:propTypes.number, 
      data:propTypes.number 
     } 

Display類App類的子類App類的,它就像是從「道具類型」這個

進口propTypes; 類顯示擴展React.Component {

constructor(props){ 
    super(props); 
    this.state={ 
     num:this.props.data,//This value of number is coming as undefined 
     value:0 
    } 

    } 
    render(){ 
    //console.log(this.state.data); 
    if(this.props.isClicked===true){ 
     return(<DonutChart data={this.state.num}/>) 
    }else{ 
     return(<DonutChart data={this.state.value}/>) 
     }  
    } 
} 

Display.propTypes={ 
    data:propTypes.number, 
    num:propTypes.number 
} 

而子類Display類是DonutChart類,這是這樣的

import propTypes from 'prop-types'; 
const DonutChart= React.createClass({ 
     propTypes:{ 
     data:React.PropTypes.number, 
      }, 
     getDefaultProps(){ 
     return{ 
      value:0, 
      size:116 
     } 
     }, 
     render(){ 
     //console.log(this.props.data); This comes as 0 on the console 
     return(
      <svg height={this.props.size} width={this.props.size}> 

      </svg> 

     ) 
     } 
    }) 

我得到這個錯誤爲「預期數字,但有一個字符串」錯誤在React中。數據的價值沒有傳遞給子類。這裏有什麼問題?

回答

-2

你想要this.props.data.size,你在Donutchart中的propTypes聲明在你的父組件中也是錯誤的,你只傳遞data而不是this.state.data。對於您的甜甜圈圖表,您可以使用stateless functional component,因爲您的容器組件可以處理狀態和道具,您的圖表唯一的工作是顯示信息。

+0

爲什麼this.props.data.size中的DoutChart的propTypes? – Aayushi

+0

console.log this.props並查看它包含的內容。 –

+0

無法讀取Display類中數據未定義的屬性號 – Aayushi