標籤:key ring classname 字串 world blank 最好 ... 遍曆
React中組件的用法與原生的 HTML 標籤完全一致,可以任意加入屬性,比如 <HelloWorld name="John"> ,就是 HelloWorld 組件加入一個 name 屬性,值為 John。和直接使用 <div name="John"> 不同,React組件被渲染出來之後,在渲染之後的dom節點中是不能直接看得到 name 屬性的,怎麼擷取呢?組件的屬性可以在組件類的 this.props 對象上擷取,比如 name 屬性就可以通過 this.props.name 讀取。
添加組件屬性,有一個地方需要注意,就是 class 屬性需要寫成 className ,for 屬性需要寫成 htmlFor ,這是因為 class 和 for 是 JavaScript 的保留字。
this.props.children
this.props 對象的屬性與組件的屬性一一對應,但是有一個例外,就是 this.props.children 屬性。它表示組件的所有子節點;
var NotesList = React.createClass({ render: function() { return ( <ol> { React.Children.map(this.props.children, function (child) { return <li>{child}</li>; }) } </ol> ); }});render( <NotesList> <span>hello</span> <span>world</span> </NotesList>, document.getElementById(‘testDiv‘));
渲染之後的dom節點內容如下:
<ol data-reactroot=""> <li><span>hello</span></li> <li><span>world</span></li></ol>
其中NodeList還可以改寫成:
var NotesList = React.createClass({ render: function() { return ( <ol> { (this.props.children).map((child, index) => { return <li key={index}>{child}</li>; }) } </ol> ); }});
需要注意的是這樣寫最好給li標籤添加一個key屬性,react建議這樣做。
This is a suggestions of reactjs to improve the rendering performance. By providing a unique key for each dynamically created element,
it is possibile to minimize possible DOM changes.
如果沒添加key,則會報如下的警告資訊:
Each child in an array or iterator should have a unique "key" prop.
參考自 stackoverflow
上面代碼的 NoteList 組件有兩個 span 子節點,它們都可以通過 this.props.children 讀取;
這裡需要注意, this.props.children 的值有三種可能:如果當前組件沒有子節點,它就是 undefined ;如果有一個子節點,資料類型是 object ;如果有多個子節點,資料類型就是 array 。所以,處理 this.props.children 的時候要小心。
React 提供一個工具方法 React.Children 來處理 this.props.children 。我們可以用 React.Children.map 來遍曆子節點,而不用擔心 this.props.children 的資料類型是 undefined 還是 object。更多的 React.Children 的方法,請參考官方文檔。
Protypes
組件的屬性可以接受任意值,字串、對象、函數等等都可以。有時,我們需要一種機制,驗證別人使用組件時,提供的參數是否符合要求。組件類的PropTypes屬性,就是用來驗證組件執行個體的屬性是否符合要求
class MyTitle extends React.Component { propTypes() { return { title: React.PropTypes.string.isRequired }; } render() { return (<div> {this.props.title} </div>); }}
也可以使用 createClass 的方式,和上面有一點區別;
var MyTitle = React.createClass({ propTypes: { title: React.PropTypes.string.isRequired, }, render: function() { return <h1> {this.props.title} </h1>; } });
Mytitle組件有一個title屬性。PropTypes 告訴 React,這個 title 屬性是必須的,而且它的值必須是字串,如果設定成其它類型值,則會出錯。
此外,getDefaultProps 方法可以用來設定組件屬性的預設值。
var MyTitle = React.createClass({ getDefaultProps : function () { return { title : ‘Hello World‘ }; }, render: function() { return <h1> {this.props.title} </h1>; }});...this.props
組件的 props 是設定到具體組件上的屬性 <ComponentA name=‘ccf‘>IM</ComponentA>,像是這樣的一個組件,就有一個name屬性和一個children屬性,其中children為字串 ‘IM‘;
在定義組件的時候可以通過...this.props
var Inner = React.createClass({ render: function() { return <div {...this.props}></div> }});// ...<Inner age="22">ABCDE</Inner>//
更多 propTypes 參考官方文檔。
Webpack + React 開發 03 props