React 学习笔记(9):props

props 用于父组件向子组件传递数据。

1,props 基本使用

<script type="text/babel">
	//创建组件
	class Person extends React.Component{
		render(){
			console.log(this);
			const {name,age,sex} = this.props
			return (
				<ul>
					<li>姓名:{name}</li>
					<li>性别:{sex}</li>
					<li>年龄:{age+1}</li>
				</ul>
			)
		}
	}
	//渲染组件到页面
	ReactDOM.render(<Person name="jerry" age={19}  sex="男"/>,document.getElementById('test1'))
	ReactDOM.render(<Person name="tom" age={18} sex="女"/>,document.getElementById('test2'))
	const p = {name:'老刘',age:18,sex:'女'}
	ReactDOM.render(<Person {...p}/>,document.getElementById('test3'))
</script>

小总结:

  • 传递给组件的 props 会保存在组件实例的 props 属性中。
  • 传递 props 的方式是在子组件的标签上使用 key = value,如果传递数据的类型是数字或者函数类型的话,则应该使用 key = { value },jsx 中的 {  } 表示其内部为 js 表达式。
  • 如果 props 已经被组织成一个对象的话,可以在子组件标签上使用 { ...object } 将对象中的数据都展开成 props 传递给子组件。

2,props 的类型限制和默认值

props 是父组件传递给子组件的数据,为了避免父组件传递错误的数据类型,所以需要对 props 进行类型限制。

除了类型限制,props 还能设置默认值,当父组件没有传递指定的 props 时,默认值会起作用。

类型限制和默认值的写法如下所示:

class Person extends React.Component{

	constructor(props){
        // 如果想在 constructor 中使用 this.props 的话,
        // 则 constructor() 应该接受 props,并且调用 super(props),
        // 否则 this.props 就是 undefined。
		super(props)
		console.log('constructor',this.props);
	}

	//对标签属性进行类型、必要性的限制
	static propTypes = {
		name:PropTypes.string.isRequired, //限制name必传,且为字符串
		sex:PropTypes.string,//限制sex为字符串
		age:PropTypes.number,//限制age为数值
	}

	//指定默认标签属性值
	static defaultProps = {
		sex:'男',//sex默认值为男
		age:18 //age默认值为18
	}
}

3,函数式组件使用 props

除了类式组件,还有函数式组件,函数式组件也可以使用 props。函数式组件 props、类型限制以及默认值写法如下所示:

<script type="text/babel">
	//创建组件
	function Person (props){
		const {name,age,sex} = props
		return (
				<ul>
					<li>姓名:{name}</li>
					<li>性别:{sex}</li>
					<li>年龄:{age}</li>
				</ul>
			)
	}
	Person.propTypes = {
		name:PropTypes.string.isRequired, //限制name必传,且为字符串
		sex:PropTypes.string,//限制sex为字符串
		age:PropTypes.number,//限制age为数值
	}

	//指定默认标签属性值
	Person.defaultProps = {
		sex:'男',//sex默认值为男
		age:18 //age默认值为18
	}
	//渲染组件到页面
	ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1'))
</script>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值