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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值