各位好,上一篇文章我們介紹了React基礎(chǔ)元素的使用和JSX等一些知識,現(xiàn)在我們繼續(xù)來學(xué)習(xí)React。
組件
組件的概念想必大家都已經(jīng)明白,就是一些常用功能的模塊化,可以大大提高項目構(gòu)建速度。并且組件將UI分割成獨立的、可重用的部分,并將問題集中到一個地方。
從概念上來講,React的組件有些像JS的Function,舉個栗子:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
看起來和函數(shù)一模一樣。下面我們用ES6的Class來創(chuàng)建組件:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
將兩個組件渲染在頁面之后,在視覺效果上完全一樣,但是后者具有更多的特性,我們后面再詳細討論。
注意:組件名稱一定要以大寫字母開頭。
渲染組件
在上一篇文章中,我們介紹了React element可以代表一個標簽:
const element = <h1>Hello, world</h1>;
其實她也可以代表一個組件:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
element,
document.getElementById('root')
);
類似的,我們使用 ReactDOM.render()將其渲染在頁面上。
你可以在CodePen上嘗試一下,會在頁面打印出“Hello,Sara”。
組裝組件
組件的輸出能夠嵌套別的組件,這給了我們相當靈活的編碼空間,你可隨意的設(shè)計和抽象你的頁面組件結(jié)構(gòu)。
我們舉個簡單的例子:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
你可以在CodePen上嘗試一下,會在頁面打印出
Hello,Sara
Hello,Cahal
Hello,Edite
提取組件
不要害怕細化你的代碼,通常有效的提取能夠大大提高代碼的可閱讀行和可維護性。舉個例子:
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<Avatar user={props.author} />
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
這是一個用戶評論的組件,其實這么分也能用,但是還是有點麻煩,現(xiàn)在我們再來細化一下:
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">
{props.user.name}
</div>
</div>
);
}
function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} />
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
這樣看起來是不是更加清晰明了?
下一節(jié),我們講的是組件的狀態(tài)和生命周期,這是重中之重,所以我打算單獨作為一節(jié)來將。
好的,先寫這么多。如果對你的學(xué)習(xí)有用,請關(guān)注我~~