1. 程式人生 > >react context prop-types

react context prop-types

child render 方便 bsp val 所有組 pre contex 通過

react裏面的context(上下文)的用途:

  我們都知道在 React 中父子組件可以通過 props 自頂向下的傳遞數據。但是當組件深度嵌套時,從頂層組件向最內層組件傳遞數據就不那麽方便了。手動在每一層組件上逐級傳遞 prop 不僅書寫起來很繁瑣同時還會為夾在中間的組件引入不必要的 prop。這時 Context API 就派上用場了。你只需要在外層組件上聲明要傳遞給子組件的 Context,就可以在父級下的所有組件裏面訪問到你需要的數據。

用法:

1 class Parent extends React.Component {
2   getChildContext() { //現在父級組件裏面這樣去寫你要傳下去的數據
3 return {color: "purple"}; 4 } 5 } 6 7 Parent.childContextTypes = {//在定義父組件之後 一定要寫PropType(類型檢測),否則報錯,執行不了 8 color: PropTypes.string 9 };

 1 class Child extends React.Component {
 2   render() {
 3     return (
 4       <p>
 5         {this.context.color}//在子組件裏面通過該方法直接調用
 6       </p>
 7
); 8 } 9 } 10 11 Child.contextTypes = {//必須進行類型檢測,如果沒有的話,不會報錯,但是會沒有該值 12 color: PropTypes.string 13 };

總結:

  父組件需要用getChildContext()方法 return一個對象,裏面以key:val的形式 傳遞你要傳遞的信息

  父組件要對要傳輸的值進行類型檢測,否則會報錯

  子組件要用this.context[key] 調用你需要的數據

  子組件也需要對你需要的值進行類型檢測,否則沒有該值

react context prop-types