Sian 发表于 2017-12-25 16:06:32

第五讲 React组件属性的验证propTypes和默认值getDefaultProps

1、前面有讲到自定义一个组件一般的写法是在React.createClass()方法中传入的对象实现render部分;
    var MyTitle = React.createClass({
      render:function(){
      return <h1>{this.props.title}</h1>;
      }
    });
2、其实这个对象中除了render外还有其他的方面的实现,如属性验证propTypes,写法和render类似
    var MyTitle = React.createClass({
      propTypes:function(){
      // 验证title属性,React.propTypes.string.isRequest为必须为字符串
      title:React.propTypes.string.isRequest
      },
      render:function(){
      return <h1>{this.props.title}</h1>;
      }
    });
2.1、加上了属性验证后,在MyTitle组件中如果有title属性值的赋值则必须为字符串,如果不是则报错;
    ReactDOM.render(
      // 不显示<MyTitle title=123 />
      <MyTitle title="abc" />,
      document.getElementById("container")
    );
3、类似属性验证的propTypes还有默认值getDefaultProps,写法也一样
    var MyTitle = React.createClass({
      // 验证title属性,React.propTypes.string.isRequest为必须为字符串
      propTypes:function(){
      title:React.propTypes.string.isRequest
      },
      // 设置默认值,title如果为空则显示sian
      getDefaultProps:function(){
      return{
          title:"sian"
      }
      },
      render:function(){
      return <h1>{this.props.title}</h1>;
      }
    });

    ReactDOM.render(
      // 不显示<MyTitle title=123 />
      <MyTitle />,
      document.getElementById("container")
    );
4、效果演示链接:http://www.yusian.com/react/props/others.html
页: [1]
查看完整版本: 第五讲 React组件属性的验证propTypes和默认值getDefaultProps