本文摘自PHP中文网,作者清浅,侵删。

Props(属性)
是组件自身的属性,props中的属性与组件属性一一对应。负责传递信息
1、父组件向子组件传递数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //定义webName组件,负责输出名字
var webName = React.createClass({
render : function() {
return < h1 >{this.props.webname} </ h1 >;
}
})
//定义webLink组件,负责跳转链接
var webLink = React.createClass({
render : function() {
return < a href={this.props.weblink}>{this.props.weblink}</ a >
}
})
var webShow = React.createClass({
render : function(){
< div >
< webName webname={this.props.webname}/>
< webLink weblink={this.props.weblink}/>
</ div >
}
})
//渲染
ReactDom.render{
return function() {
< webShow webname = "hellp" weblink = "www.baidu.com" />,
document.getElementById("container")
}
}
|
2、设置默认属性
通过static defaultProps = {}这种固定的格式来给一个组件添加默认属性
1 2 3 4 5 6 7 8 9 10 11 12 13 | export default class MyView extends Component {
static defaultProps = {
age: 12,
sex: '男'
}
render() {
return < Text
style={{backgroundColor: 'cyan'}}>
你好{this.props.name}{'\n'}年龄{this.props.age}{'\n'}性别{this.props.sex}
</ Text >
}
}
|
3、属性检查
通过 static propTypes = {} 这种固定格式来设置属性的格式,比如说我们将 age 设置为 number 类型
1 2 3 4 5 6 7 8 9 | var title = React.createClass({
propTypes={
//title类型必须是字符串
title : React.PropTypes.string.isRequired
},
render : function() {
return < h1 >{this.props.title}</ h1 >
}
})
|
延展操作符 ... 是 ES6 语法的新特性。...this.porps,一种语法,将父组件中全部属性复制给子组件
2 父组件向子组件传递调用函数,用来通知父组件消息。
3 用来作为子组件逻辑判断的标示,渲染的样式等
4 children,不是跟组件对应的属性,表示组件所有子节点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //定义webName组件,负责输出名字
var listCompont = React.createClass({
render : function() {
return
< ul >
{
/**
* 列表项内容不固定,需要在创建模版时确定。利用this.props.children传递显示内容
* 获取到内容后,需要遍历children,逐项设置。利用React.Children.map方法
**/
React.Children.map(this.props.children,function(child) {
//child是遍历得到父组件子节点
return < li >{child}</ li >;
})
}
</ ul >;
}
})
//渲染
ReactDom.render{
{
< listCompont >
< h1 >hello</ h1 >
< a href = "link" >"www.baidu.com"</ a >
</ listCompont >
},
document.getElementById("container")
}
|
总结:以上就是本篇文章的全部内容了,希望对大家有所帮助
以上就是Props属性如何设置的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
html5实践-详细介绍css3中的几个属性text-shadow、box-shadow和border-radius
layui怎么设置复选框
position的几个属性的作用分别是什么
行内属性什么意思?
在css中设置边框可以用哪些属性
html的元素如何设置焦点
css中更改透明度的属性是什么
如何使用jquery对属性进行获取、设置和删除
bootstrap如何设置行间距
如何使用html的title属性
更多相关阅读请进入《属性》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » Props属性如何设置