prop 父傳子
在 React
應用中,數據通過 props
的傳遞,從父組件流向子組件
Child
是一個 React
組件類,或者說是一個 React
組件類型。
一個組件接收一些參數
,我們把這些參數
叫做 props
(“props” 是 “properties” 簡寫),然后通過 render
方法返回需要展示在屏幕上的視圖的層次結構
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 來實現所謂“記憶”的功能。
可以通過在React
組件的構造函數中設置 this.state
來初始化 state
。this.state
應該被視為一個組件的私有屬性。我們在 this.state
中存儲當前每個方格(Child
)的值,並且在每次方格被點擊的時候改變這個值。
首先,我們向這個 class
中添加一個構造函數
,用來初始化 state
:
在 JavaScript class 中,每次你定義其子類的構造函數時,都需要調用
super
方法。因此,在所有含有構造函數的的React
組件中,構造函數必須以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 數據提升至其共同的父組件當中保存
當你遇到需要同時獲取多個子組件數據,或者兩個組件之間需要相互通訊的情況時,需要把子組件的 state
數據提升至其共同的父組件
當中保存。之后父組件可以通過 props
將狀態數據傳遞到子組件當中。這樣應用當中所有組件的狀態數據就能夠更方便地同步共享了。
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 中,每次你定義其子類的構造函數時,都需要調用 super 方法。因此,在所有含有構造函數的的 React 組件中,構造函數必須以 super(props) 開頭
+ this.state = {
+ values: Array(9).fill(null)
+ };
+ }
+ handleClick(i){
+ const values=this.state.values.slice();// .slice() 方法創建了 squares 數組的一個副本,而不是直接在現有的數組上進行修改.簡化復雜的功能-不直接在數據上修改可以讓我們追溯並復用游戲的歷史記錄;跟蹤數據的改變;確定在 React 中何時重新渲染
+ 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>
);
}
}
函數組件
如果你想寫的組件只包含一個 render
方法,並且不包含 state
,那么使用函數組件就會更簡單。
我們不需要定義一個繼承於 React.Component
的類,我們可以定義一個函數
,這個函數接收 props
作為參數,然后返回需要渲染的元素
。函數組件寫起來並不像 class 組件那么繁瑣,很多組件都可以使用函數組件來寫。
function Child(props) {
return (
<button className="acceptValue" onClick={props.onClick}>
{props.value}
</button>
);
}
注意
當我們把Square
修改成函數組件時,我們同時也把onClick={() => this.props.onClick()}
改成了更短的onClick={props.onClick}
(注意兩側都沒有括號)。
向事件處理程序傳遞參數
在循環中,通常我們會為事件處理函數傳遞額外的參數。例如,若 id 是你要刪除那一行的 ID,以下兩種方式都可以向事件處理函數傳遞參數:
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
在這兩種情況下,React 的事件對象 e 會被作為第二個參數傳遞。如果通過箭頭函數
的方式,事件對象必須顯式
的進行傳遞,而通過 bind
的方式,事件對象以及更多的參數將會被隱式
的進行傳遞。
與運算符 &&
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
總是會返回 expression
, 而 false && expression
總是會返回 false
。
因此,如果條件是 true
,&&
右側的元素就會被渲染,如果是 false
,React 會忽略並跳過它。
三目運算符
使用 JavaScript 中的三目運算符 condition ? true : false
。
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={this.handleLogoutClick} />
) : (
<LoginButton onClick={this.handleLoginClick} />
)}
</div>
);
}
就像在 JavaScript 中一樣,你可以根據團隊的習慣來選擇可讀性更高的代碼風格。需要注意的是,如果條件變得過於復雜,那你應該考慮如何提取組件。
阻止組件渲染
在極少數情況下,你可能希望能隱藏組件
,即使它已經被其他組件渲染。若要完成此操作,你可以讓 render 方法直接返回 null
,而不進行任何渲染。
下面的示例中,
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
當元素沒有確定 id
的時候,萬不得已
你可以使用元素索引 index
作為 key:
const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
<li key={index}>
{todo.text}
</li>
);
如果列表項目的順序
可能會變化,我們不建議
使用索引
來用作 key
值,因為這樣做會導致性能變差
,還可能引起組件狀態的問題
。可以看看 Robin Pokorny 的深度解析使用索引作為 key 的負面影響這一篇文章。
如果你選擇不指定顯式的 key 值
,那么 React 將默認
使用索引
用作為列表項目的 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('你喜歡的風味是: ' + this.state.value);
+ event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
選擇你喜歡的風味:
+ <select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">葡萄柚</option>
</select>
</label>
+ <input type="submit" value="提交" />
</form>
);
}
}
你可以將數組傳遞到 value 屬性中,以支持在 select 標簽中選擇多個選項:
<select multiple={true} value={['B', 'C']}>
注意點
組件名稱
必須以大寫字母
開頭。componentDidMount()
方法會在組件已經被渲染到 DOM 中后運行- 構造函數是唯一可以給
this.state
賦值的地方,this.setState({});
數據是向下流動的
,state
為局部
的或是封裝
的。除了擁有並設置了它的組件
,其他組件
都無法訪問
,組件可以選擇把它的state
作為props
向下
傳遞到它的子組件
.這通常會被叫做“自上而下”
或是“單向”
的數據流
。任何的state
總是所屬於特定的組件,而且從該state
派生的任何數據或 UI 只能影響樹中“低於”
它們的組件React
事件的命名采用小駝峰式
(camelCase
),而不是純小寫。key
應該在數組的上下文
中被指定.在map()
方法中的元素需要設置key
屬性.key
只是在兄弟節點之間必須唯一- 如果你的組件中需要使用
key
屬性的值,請用其他屬性名顯式傳遞
這個值.無法通過props
讀出props.key
- JSX 允許在大括號中嵌入任何表達式