浅谈React的props验证、默认值、传递

来源:互联网 发布:碧蓝幻想 知乎 编辑:程序博客网 时间:2024/06/05 16:33

1、用 React.PropTypes.element可以指定某props属性必须是一个React元素。

正确示范1:

var MyBox = React.createClass({propTypes: {children: React.PropTypes.element.isRequired},render: function() {return (<div>{this.props.children} </div>);}});ReactDOM.render(<MyBox><span>Hello, react!</span></MyBox>,document.getElementById('timeBox'));

正确示范2:

var MyBox = React.createClass({      propTypes: {          children: React.PropTypes.element.isRequired      },      render: function() {          return (              <div>                  {this.props.children}               </div>          );      }  });  ReactDOM.render(      <MyBox>  <div><span>Hello</span>  <span> react!</span>  </div>    </MyBox>,      document.getElementById('timeBox')  ); 

错误示范1:

var MyBox = React.createClass({propTypes: {children: React.PropTypes.element.isRequired},render: function() {return (<div>{this.props.children} </div>);}});ReactDOM.render(<MyBox>Hello, react!</MyBox>,document.getElementById('timeBox'));

错误示范2:

var MyBox = React.createClass({      propTypes: {          children: React.PropTypes.element.isRequired      },      render: function() {          return (              <div>                  {this.props.children}               </div>          );      }  });  ReactDOM.render(      <MyBox>  <span>Hello</span>  <span> react!</span>      </MyBox>,      document.getElementById('timeBox')  ); 

更多关于React类型验证PropsType的介绍请见:http://blog.csdn.net/zhouziyu2011/article/details/70842310


2、React 支持以声明式的方式来定义 props 的默认值

var MyBox = React.createClass({getDefaultProps: function() {return {id: 'text'};},render: function() {return (<input id={this.props.id} type="text"/> );}});ReactDOM.render(<MyBox />,document.getElementById('timeBox'));


3、常用的React组件只是对HTML做简单扩展,可以复制任何传进组件的HTML属性到底层的HTML元素上。

var MyLink = React.createClass({render: function() {return <a {...this.props}>{this.props.children}</a>;}});ReactDOM.render(<MyLink href="https://www.baidu.com">Click here!</MyLink>,document.getElementById('timeBox'));

更多关于JSX的新语法——展开属性(...操作符)的介绍请见:http://blog.csdn.net/zhouziyu2011/article/details/70807803

1 0
原创粉丝点击