Props属性设置的方法:Props属性是组件自身的属性,负责传递消息,可以通过static defaultProps格式来设置默认属性,static propTypes格式来设置属性的格式
Props(属性)
是组件自身的属性,props中的属性与组件属性一一对应。负责传递信息
1 父组件向子组件传递数据
//定义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") }}
设置默认属性
通过 static defaultProps = {} 这种固定的格式来给一个组件添加默认属性
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> }}
属性检查
通过 static propTypes = {} 这种固定格式来设置属性的格式,比如说我们将 age 设置为 number 类型
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,不是跟组件对应的属性,表示组件所有子节点。
//定义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属性如何设置的详细内容,更多请关注php中文网其它相关文章!