prop 父?jìng)髯?/h2>
在 React
應(yīng)用中,數(shù)據(jù)通過 props
的傳遞农猬,從父組件流向子組件
Child
是一個(gè) React
組件類赡艰,或者說是一個(gè) React
組件類型。
一個(gè)組件接收一些參數(shù)
斤葱,我們把這些參數(shù)
叫做 props
(“props” 是 “properties” 簡(jiǎn)寫)慷垮,然后通過 render
方法返回需要展示在屏幕上的視圖的層次結(jié)構(gòu)
props.children
class Child extends React.Component {
render() {
return (
<button className=acceptValue" onClick={() => alert('click')}>
父組件流向子組件的值為: {this.props.value}
</button>
);
}
}
// 用法示例: <Child value="X" />
class Father extends React.Component {
renderChild(i) {
return <Child value={i} />;
}
render() {
return (
<div>
<div className="provideValue"> {this.renderChild(0)}</div>
</div>
);
}
}
state 來實(shí)現(xiàn)所謂“記憶”的功能揖闸。
可以通過在React
組件的構(gòu)造函數(shù)中設(shè)置 this.state
來初始化 state
。this.state
應(yīng)該被視為一個(gè)組件的私有屬性料身。我們?cè)?this.state
中存儲(chǔ)當(dāng)前每個(gè)方格(Child
)的值汤纸,并且在每次方格被點(diǎn)擊的時(shí)候改變這個(gè)值。
首先惯驼,我們向這個(gè) class
中添加一個(gè)構(gòu)造函數(shù)
蹲嚣,用來初始化 state
:
在 JavaScript class 中,每次你定義其子類的構(gòu)造函數(shù)時(shí)祟牲,都需要調(diào)用
super
方法隙畜。因此,在所有含有構(gòu)造函數(shù)的的React
組件中说贝,構(gòu)造函數(shù)必須以super(props)
開頭议惰。
class Child extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ value: null,
+ };
+ }
render() {
return (
- <button className="acceptValue" onClick={() => alert('click')}>
+ <button
+ className="acceptValue"
+ onClick={() => this.setState({value: 'X'})}
+ >
- {this.props.value}
+ {this.state.value}
</button>
);
}
}
class Father extends React.Component {
renderChild(i) {
+ return <Child/>;
}
render() {
return (
<div>
<div className="provideValue"> {this.renderChild(0)}</div>
</div>
);
}
}
子組件的 state 數(shù)據(jù)提升至其共同的父組件當(dāng)中保存
當(dāng)你遇到需要同時(shí)獲取多個(gè)子組件數(shù)據(jù),或者兩個(gè)組件之間需要相互通訊的情況時(shí)乡恕,需要把子組件的 state
數(shù)據(jù)提升至其共同的父組件
當(dāng)中保存言询。之后父組件可以通過 props
將狀態(tài)數(shù)據(jù)傳遞到子組件當(dāng)中。這樣應(yīng)用當(dāng)中所有組件的狀態(tài)數(shù)據(jù)就能夠更方便地同步共享了傲宜。
class Child extends React.Component {
render() {
return (
+ <button
+ className="acceptValue"
+ onClick={() => this.props.onClick()}
+ >
{this.props.value}
- {this.state.value}
</button>
);
}
}
class Father extends React.Component {
+ constructor(props) {
+ super(props);//在 JavaScript class 中运杭,每次你定義其子類的構(gòu)造函數(shù)時(shí),都需要調(diào)用 super 方法函卒。因此辆憔,在所有含有構(gòu)造函數(shù)的的 React 組件中,構(gòu)造函數(shù)必須以 super(props) 開頭
+ this.state = {
+ values: Array(9).fill(null)
+ };
+ }
+ handleClick(i){
+ const values=this.state.values.slice();// .slice() 方法創(chuàng)建了 squares 數(shù)組的一個(gè)副本报嵌,而不是直接在現(xiàn)有的數(shù)組上進(jìn)行修改.簡(jiǎn)化復(fù)雜的功能-不直接在數(shù)據(jù)上修改可以讓我們追溯并復(fù)用游戲的歷史記錄;跟蹤數(shù)據(jù)的改變;確定在 React 中何時(shí)重新渲染
+ values[i]='X'
+ this.setState({values:values});
+ }
renderChild(i) {
return (
<Child
+ value={this.state.values[i]}
+ onClick={() => this.handleClick(i)}
/>
);
}
render() {
return (
<div>
<div className="provideValue">
{this.renderChild(0)}
</div>
</div>
);
}
}
函數(shù)組件
如果你想寫的組件只包含一個(gè) render
方法虱咧,并且不包含 state
,那么使用函數(shù)組件就會(huì)更簡(jiǎn)單锚国。
我們不需要定義一個(gè)繼承于 React.Component
的類腕巡,我們可以定義一個(gè)函數(shù)
,這個(gè)函數(shù)接收 props
作為參數(shù)血筑,然后返回需要渲染的元素
绘沉。函數(shù)組件寫起來并不像 class 組件那么繁瑣,很多組件都可以使用函數(shù)組件來寫豺总。
function Child(props) {
return (
<button className="acceptValue" onClick={props.onClick}>
{props.value}
</button>
);
}
注意
當(dāng)我們把Square
修改成函數(shù)組件時(shí)梆砸,我們同時(shí)也把onClick={() => this.props.onClick()}
改成了更短的onClick={props.onClick}
(注意兩側(cè)都沒有括號(hào))。
向事件處理程序傳遞參數(shù)
在循環(huán)中园欣,通常我們會(huì)為事件處理函數(shù)傳遞額外的參數(shù)帖世。例如,若 id 是你要?jiǎng)h除那一行的 ID,以下兩種方式都可以向事件處理函數(shù)傳遞參數(shù):
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
在這兩種情況下日矫,React 的事件對(duì)象 e 會(huì)被作為第二個(gè)參數(shù)傳遞赂弓。如果通過箭頭函數(shù)
的方式,事件對(duì)象必須顯式
的進(jìn)行傳遞哪轿,而通過 bind
的方式盈魁,事件對(duì)象以及更多的參數(shù)將會(huì)被隱式
的進(jìn)行傳遞。
與運(yùn)算符 &&
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
+ {unreadMessages.length > 0 &&
+ <h2>
+ You have {unreadMessages.length} unread messages.
+ </h2>
}
</div>
);
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
<Mailbox unreadMessages={messages} />,
document.getElementById('root')
);
在 JavaScript 中窃诉,true && expression
總是會(huì)返回 expression
, 而 false && expression
總是會(huì)返回 false
杨耙。
因此,如果條件是 true
飘痛,&&
右側(cè)的元素就會(huì)被渲染珊膜,如果是 false
,React 會(huì)忽略并跳過它宣脉。
三目運(yùn)算符
使用 JavaScript 中的三目運(yùn)算符 condition ? true : false
车柠。
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={this.handleLogoutClick} />
) : (
<LoginButton onClick={this.handleLoginClick} />
)}
</div>
);
}
就像在 JavaScript 中一樣,你可以根據(jù)團(tuán)隊(duì)的習(xí)慣來選擇可讀性更高的代碼風(fēng)格塑猖。需要注意的是竹祷,如果條件變得過于復(fù)雜,那你應(yīng)該考慮如何提取組件羊苟。
阻止組件渲染
在極少數(shù)情況下塑陵,你可能希望能隱藏組件
,即使它已經(jīng)被其他組件渲染蜡励。若要完成此操作令花,你可以讓 render 方法直接返回 null
,而不進(jìn)行任何渲染巍虫。
下面的示例中彭则,<WarningBanner /> 會(huì)根據(jù) prop 中 warn 的值來進(jìn)行條件渲染鳍刷。如果 warn 的值是 false占遥,那么組件則不會(huì)渲染:
function WarningBanner(props) {
+ if (!props.warn) {
+ return null;
+ }
return (
<div className="warning">
Warning!
</div>
);
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {showWarning: true};
this.handleToggleClick = this.handleToggleClick.bind(this);
}
handleToggleClick() {
this.setState(state => ({
showWarning: !state.showWarning
}));
}
render() {
return (
<div>
+ <WarningBanner warn={this.state.showWarning} />
<button onClick={this.handleToggleClick}>
{this.state.showWarning ? 'Hide' : 'Show'}
</button>
</div>
);
}
}
ReactDOM.render(
<Page />,
document.getElementById('root')
);
key
當(dāng)元素沒有確定 id
的時(shí)候,萬(wàn)不得已
你可以使用元素索引 index
作為 key:
const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
<li key={index}>
{todo.text}
</li>
);
如果列表項(xiàng)目的順序
可能會(huì)變化输瓜,我們不建議
使用索引
來用作 key
值瓦胎,因?yàn)檫@樣做會(huì)導(dǎo)致性能變差
,還可能引起組件狀態(tài)的問題
尤揣∩Π。可以看看 Robin Pokorny 的深度解析使用索引作為 key 的負(fù)面影響這一篇文章。
如果你選擇不指定顯式的 key 值
北戏,那么 React 將默認(rèn)
使用索引
用作為列表項(xiàng)目的 key
值负芋。
表單
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
+ this.handleChange = this.handleChange.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
+ this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('你喜歡的風(fēng)味是: ' + this.state.value);
+ event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
選擇你喜歡的風(fēng)味:
+ <select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">葡萄柚</option>
</select>
</label>
+ <input type="submit" value="提交" />
</form>
);
}
}
你可以將數(shù)組傳遞到 value 屬性中,以支持在 select 標(biāo)簽中選擇多個(gè)選項(xiàng):
<select multiple={true} value={['B', 'C']}>
注意點(diǎn)
-
組件名稱
必須以大寫字母
開頭嗜愈。 -
componentDidMount()
方法會(huì)在組件已經(jīng)被渲染到 DOM 中后運(yùn)行 - 構(gòu)造函數(shù)是唯一可以給
this.state
賦值的地方,this.setState({});
-
數(shù)據(jù)是向下流動(dòng)的
,state
為局部
的或是封裝
的旧蛾。除了擁有并設(shè)置了它的組件
莽龟,其他組件
都無(wú)法訪問
,組件可以選擇把它的state
作為props
向下
傳遞到它的子組件
.這通常會(huì)被叫做“自上而下”
或是“單向”
的數(shù)據(jù)流
。任何的state
總是所屬于特定的組件锨天,而且從該state
派生的任何數(shù)據(jù)或 UI 只能影響樹中“低于”
它們的組件 -
React
事件的命名采用小駝峰式
(camelCase
)毯盈,而不是純小寫。 -
key
應(yīng)該在數(shù)組的上下文
中被指定.在map()
方法中的元素需要設(shè)置key
屬性.key
只是在兄弟節(jié)點(diǎn)之間必須唯一 - 如果你的組件中需要使用
key
屬性的值病袄,請(qǐng)用其他屬性名顯式傳遞
這個(gè)值.無(wú)法通過props
讀出props.key
- JSX 允許在大括號(hào)中嵌入任何表達(dá)式