React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > React Context

React Context详解使用方法

作者:码农小菲

Context提供了一个无需为每层组件手动添加props,就能在组件树间进行数据传递的方法。在一个典型的 React 应用中,数据是通过props属性自上而下(由父及子)进行传递的,但这种做法对于某些类型的属性而言是极其繁琐的

一、概述

二、API

React.createContext

const MyContext = React.createContext(defaultValue)

Context.Provider

  const MyContext = React.createContext(defaultValue)
  <MyContext.Provider value={xxx}> ... </MyContext.Provider>

Class.contextType

class MyClass extends React.Component {
  componentDidMount() {
    let value = this.context;
    /* 在组件挂载完成后,使用 MyContext 组件的值来执行一些有副作用的操作 */
  }
  componentDidUpdate() {
    let value = this.context;
    /* ... */
  }
  componentWillUnmount() {
    let value = this.context;
    /* ... */
  }
  render() {
    let value = this.context;
    /* 基于 MyContext 组件的值进行渲染 */
  }
}
MyClass.contextType = MyContext;

Context.Consumer

<MyContext.Consumer>
   {value => /* 基于 context 值进行渲染*/}
</MyContext.Consumer>

Context.displayName

const MyContext = React.createContext()
MyContext.displayName = 'MyDisplayName'
<MyContext.Provider> //在 DevTools 中显示的标签:MyDisplayName.Provider  
<MyContext.Consumer>//在 DevTools 中显示的标签:MyDisplayName.Consumer  
//如果没有 MyContext.displayName = 'MyDisplayName' ,则显示Context.Provider、Context.Consumer

在 DevTools 中需要显示的内容

三、使用

1.自定义Context (类组件中使用)

//ThemeContext.js
import React from 'react'
export const ThemeContext = React.createContext('light')
//themed-button.js
//在需要的位置使用 Class.contextType
import React, { Component } from 'react';
import ThemeContext from "./context/ThemeContext.js";

class ThemedButton extends Component {
	static contextType = ThemeContext;
	render() {
		return <button>{this.context}</button>;
	}
}
export default ThemedButton
//app.js
//上下文包裹组件 Context.Provider
import ThemeContext from './context/ThemeContext.js';
import ThemedButton from './ThemedButton.js';
import './App.css';
function App() {
  return (
    <ThemeContext.Provider value='dark'> //dark将默认值light覆盖
      <div className="App">
        <header className="App-header">
          <ThemedButton />
        </header>
      </div>
    </ThemeContext.Provider>
  );
}
export default App;

2.使用Consumer支持获取多个Context上的值

需要多个上下文的值时可以使用Consumer

//ThemeContext.js
import React from 'react'
const ThemeContext = React.createContext('light')
ThemeContext.displayName = 'ThemeContext'
export default ThemeContext
//UserContext.js
import React from 'react'
const UserContext = React.createContext('guest')
UserContext.displayName = 'UserContext'
export default UserContext
//app.js
//使用Provider赋值:
import React, { Component } from 'react';
import ThemeContext from './context/ThemeContext.js';
import UserContext from './context/UserContext.js';
import ThemedButton from './ThemedButton.js';
import './App.css';
class App extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
        <ThemeContext.Provider value={'dark'}>
          <div className="App">
            <UserContext.Provider value={'user'}>
              <header className="App-header">
                <ThemedButton />
              </header>
            </UserContext.Provider>
          </div>
        </ThemeContext.Provider>
    );
  }
}
export default App
//themed-button.js
import React, { Component } from 'react';
import ThemeContext from "./context/ThemeContext.js";
import UserContext from "./context/UserContext.js";
class ThemedButton extends Component {
	render() {
		return (
			<>
				<ThemeContext.Consumer>
					{theme => <div>{theme}</div>}
				</ThemeContext.Consumer>
				<UserContext.Consumer>
					{user => <div>{user}</div>}
				</UserContext.Consumer>
			</>
		);
	}
}
export default ThemedButton

3.useContext使用(函数式组件中使用)

react原生Hook ,让函数式组件也可以使用Context,而且支持多个不同类型的context

//ThemeContext.js
import React from 'react'
const ThemeContext = React.createContext('light')
ThemeContext.displayName = 'ThemeContext'
export default ThemeContext
//UserContext.js
import React from 'react'
const UserContext = React.createContext('guest')
UserContext.displayName = 'UserContext'
export default UserContext
//app.js
//使用Provider赋值:
import React, { Component } from 'react';
import ThemeContext from './context/ThemeContext.js';
import UserContext from './context/UserContext.js';
import ThemedButton from './ThemedButton.js';
import './App.css';
const App = () => {
  render() {
    return (
        <ThemeContext.Provider value={'dark'}>
          <div className="App">
            <UserContext.Provider value={'user'}>
              <header className="App-header">
                <ThemedButton />
              </header>
            </UserContext.Provider>
          </div>
        </ThemeContext.Provider>
    );
  }
}
export default App
//themed-button.js
import { useContext } from 'react'
import ThemeContext  from './context/ThemeContext'
import UserContext from './context/UserContext'
const ThemedButton = () => {
 const theme = useContext(ThemeContext)
 const user = useContext(UserContext)
 return (
    <>
		<div>{theme}</div>
		<div>{user}</div>
	</>
 )
}
export default ThemedButton

到此这篇关于React Context详解使用方法的文章就介绍到这了,更多相关React Context内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文