Props屬性的設置方法?這個問題可能是我們日常學習或工作經常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家帶來的參考內容,讓我們一起來看看吧!
Props屬性設置的方法:Props屬性是組件自身的屬性,負責傳遞消息,可以通過static defaultProps格式來設置默認屬性,static propTypes格式來設置屬性的格式

Props(屬性)
是組件自身的屬性,props中的屬性與組件屬性一一對應。負責傳遞信息
1 父組件向子組件傳遞數據
//定義webName組件,負責輸出名字
var webName = React.createClass({
render : function() {
return <h2>{this.props.webname} </h2>;
}
})
//定義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 <h2>{this.props.title}</h2>
}
})延展操作符 ... 是 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>
<h2>hello</h2>
<a href="link">"www.baidu.com"</a>
</listCompont>
},
document.getElementById("container")
}感謝各位的閱讀!看完上述內容,你們對Props屬性的設置方法大概了解了嗎?希望文章內容對大家有所幫助。如果想了解更多相關文章內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。