亲宝软件园·资讯

展开

React Context详解使用方法

码农小菲 人气:0

一、概述

二、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

加载全部内容

相关教程
猜你喜欢
用户评论