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="itread01"/>;
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="入門教學" />
<Url url="http://www.itread01.com" />
<Nickname nickname="itread01" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('example')
);
嘗試一下 ?
例項中 App 元件使用了 Name、Url 和 Nickname 元件來輸出對應的資訊。