六.PropTypes

组件的属性可以接受任意值,字符串,函数,对象。有时,我们需要一种机制,验证别人使用组件时,提供的参数是否符合要求。

组件类的 PropTypes属性。就是验证组件实例的属性是否符合要求  

var MyTitle = React.createClass({

  propTypes:{

    title:React.propTypes.string.isRequired,

  }

 

  render:function(){

    return <h1>{this.props.title}</h1>

  }

})

 

上面的MyTitle 有个title属性。PropTypes告诉React这个title属性是必须的。而且它的值是字符串,现在我们设置title的值是一个数值。

var data = 123

ReactDOM.render(

  <MyTitle title={data}/>

  document.body

)

这样一来title就通过不了验证,控制台会显示一行错误信息。

Warning: Failed propType: Invalid prop `title` of type `number` supplied to `MyTitle`, expected `string`

此外 getDefaultProps 可以用来设置属性的默认值

var MyTitle = React.createClass({

  getDefaultProps: function(){

    return (

      title: "Hello world"

    )

  },

 

  render:function(){

    return <h1>{this.props.title}</h1>

  }

})

 

ReactDOM.render({

  <MyTitle />,

  document.body

})

posted @ 2016-09-10 14:11  约翰·史密斯  阅读(2876)  评论(0编辑  收藏  举报