Props(屬性)
組件創(chuàng)建的時(shí)候需要用不同的參數(shù)進(jìn)行定制虎囚,這些定制的參數(shù)就是props(屬性)验残,可為組件內(nèi)部屬性,也可為外部屬性泛释。
props 是組件自身的屬性對(duì)象,一般用于嵌套的內(nèi)外層組件中温算,負(fù)責(zé)傳遞信息(通常是由浮層組件向子層組件傳遞)
注意:props對(duì)象中的屬性與組件的屬性是一一對(duì)應(yīng)怜校,不要直接去修改props中屬性的值
自定義的組件也可以使用props。通過在不同的場(chǎng)景使用不同的屬性定制注竿,可以盡量提高自定義組件的復(fù)用范疇茄茁。只需在render函數(shù)中引用this.props,然后按需處理即可巩割。下面是一個(gè)例子:(這是 ES6的書寫方式)
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';
class Greeting extends Component {
render() {
return (
<Text>Hello {this.props.name}!</Text>
);
}
}
class LotsOfGreetings extends Component {
render() {
return (
<View style={{alignItems: 'center'}}>
<Greeting name='Rexxar' />
<Greeting name='Jaina' />
<Greeting name='Valeera' />
</View>
);
}
}
AppRegistry.registerComponent('LotsOfGreetings', () => LotsOfGreetings);
我們?cè)?Greeting 組件中將 name 作為一個(gè)屬性來定制裙顽,這樣可以復(fù)用這一組件來制作各種不同的“問候語(yǔ)”。上面的例子把 Greeting 組件寫在JSX語(yǔ)句中宣谈,用法和內(nèi)置組件并無二致——這正是React體系的魅力所在——如果你想搭建一套自己的基礎(chǔ)UI框架愈犹,那就放手做吧!
上面的例子出現(xiàn)了一樣新的名為View的組件闻丑。View 常用作其他組件的容器漩怎,來幫助控制布局和樣式。僅僅使用props和基礎(chǔ)的Text嗦嗡、Image以及View組件扬卷,你就已經(jīng)足以編寫各式各樣的UI組件了。要學(xué)習(xí)如何動(dòng)態(tài)修改你的界面酸钦,那就需要進(jìn)一步學(xué)習(xí)State(狀態(tài))的概念。
擴(kuò)展
初始化 Props 設(shè)置默認(rèn)值
(這是 ES5 的書寫方式)
//創(chuàng)建一個(gè) ShowDefault 的組件
var ShowDefault = React.createClass({
// 初始化props 設(shè)置默認(rèn)值
getDefaultProps: function(){
return {
name: "張三",
age:18
};
},
render: function(){
return <h1>{this.props.name}{this.props.age}</h1>
}
});
ReactDOM.render(
<ShowDefault />,
document.getElementById("container")
);
...this.props
props提供的語(yǔ)法糖,可以將父組件中的全部屬性都復(fù)制給子組件
以下代碼是 React.js 的代碼寫法
var Link = React.createClass({
render: function(){
return <a {...this.props}>{this.props.name}</a>
}
});
ReactDOM.render(
<Link name="百度" />,
document.getElementById('container')
);
this.props.children
children 是一個(gè)例外,不是跟組件的屬性對(duì)應(yīng)的,表示組件的子節(jié)點(diǎn)
HTML5 中有一種標(biāo)簽:列表 <ul><ol><li>
定義一個(gè)列表組件,列表項(xiàng)中顯示的內(nèi)容,以及列表項(xiàng)的數(shù)量都由外部決定
var ListComponent = React.createClass({
render: function(){
return(
<ul>
{
/*
列表項(xiàng)的數(shù)量以及內(nèi)容不確定,在創(chuàng)建模板的時(shí)候才可以確定
利用this.props.children從父組件獲取列表項(xiàng)需要展示的列表項(xiàng)內(nèi)容
獲取到列表項(xiàng)內(nèi)容后,需要便利children,逐項(xiàng)進(jìn)行設(shè)置,
使用React.Children.map方法
返回值:數(shù)組對(duì)象.這里數(shù)組中的元素是<li>
*/
React.Children.map(this.props.children,function(child){
// child 是遍歷得到的費(fèi)組件的子節(jié)點(diǎn)
return <li> {child}</li>
})
}
</ul>
)
}
});
ReactDOM.render(
(<ListComponent>
<h1> 百度 </h1>
<a >http://www.baidu.com</a>
</ListComponent>),
document.getElementById("container")
);
props 和 state 的區(qū)別
state 和 props 主要的區(qū)別在于 props 是不可變的,而 state 可以根據(jù)與用戶交互來改變卑硫。這就是為什么有些容器組件需要定義 state 來更新和修改數(shù)據(jù)徒恋。 而子組件只能通過 props 來傳遞數(shù)據(jù)。