Props (properties)
are the properties of the component itself. The properties in props correspond to the component properties one-to-one. Responsible for transmitting information
1. Pass data from parent component to child component
//定义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. Set default attributes
through static defaultProps = {} is a fixed format to add default properties to a component
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. Attribute checking
is done through static propTypes = {}. Set the format of the attribute, for example, we set age to number type
var title = React.createClass({ propTypes={ //title类型必须是字符串 title : React.PropTypes.string.isRequired }, render : function() { return <h1>{this.props.title}</h1> } })
Extension operator... is a new feature of ES6 syntax. ...this.porps, a syntax that copies all properties in the parent component to the child component
2 The parent component passes the calling function to the child component to notify the parent component of the message.
3 Used as a mark for logical judgment of sub-components, rendering styles, etc.
4 children, which is not an attribute corresponding to the component, represents all child nodes of the component.
//定义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") }
Summary: The above is the entire content of this article, I hope it will be helpful to everyone
The above is the detailed content of How to set the Props attribute. For more information, please follow other related articles on the PHP Chinese website!