2017-07-27 78 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