Alex Liang

React Context API 介紹

在React裡,如果Parent和Child Component之間需要傳data,最直覺的方式是透過props傳進去,然而在結構複雜的頁面中,如果得一層一層傳下去,對於之後的維謢相當的麻煩。
而Context API便是用來解決資料傳遞的問題。

在React 16.3之前,context API的使用較為不便,得在parent component class定義若干函式,

而新的context API只要定義:

  1. context provider,提供要傳遞的data
  2. context consumer,接收data

下面是一個簡單的範例,假如頁面上有三個component,分別為書藉清單、書的簡介和內容試閱,它們為階層式架構,最底層的試閱得拿到書名。

在使用context前,必須先建立實體,createContext可傳入data的預設值。接著引入context至component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const BookContext = React.createContext();

class BookList extends Componet {
constructor(props) {
super(props);

this.state = {
bookName: 'Javascript the good part'
};
}

// 傳遞資料的Component使用Provider
render() {
return (
<BookContext.Provider value={this.state}>
<BookBrief />
</BookContext.Provider>
);
}
}

// 中間這一層不需要傳context下去
function BookBrief (props) {
return (
<div>
<ContentFragment />
</div>
);
}

// 要用到context這層使用Consumer接收資料
function ContentFragment(props) {
return (
<BookContext.Consumer>
{context => context.bookName}
</BookContext.Consumer>
);
}

如此一來即可從BookList直接傳遞資料至底層的ContentFragment
不只是資料,我們也能傳函式下去,可以更方便的由Child Component呼叫Parent的函式。

參考資料:

  1. 官方文件
  2. How to use the new react contenxt API