>首页> IT >

react中context的用法是什么

时间:2022-04-21 17:38:47       来源:PHP中文网

本教程操作环境:Windows10系统、react17.0.1版、Dell G3电脑。

react中context的用法是什么

Context提供了一种新的组件之间共享数据的方式,允许数据隔代传递,而不必显式的通过组件树逐层传递props。

Context 提供了一种在组件之间共享值的方式,而不必显式地通过组件树的逐层传递 props。如果获取值和使用值的层级相隔很远,或者需要使用这个值的组件很多很分散,则可以使用Context来共享数据,避免使用大量重复的props来传递值。如果只是一个组件需要使用这个值,可以在产生这个值的位置生成这个组件,然后用props层层传递到组件实际展示的位置。

基本使用方式

1、自定义Context

import React from "react"; const ThemeContext = React.createContext("light"); export default ThemeContext;

上面的代码定义了一个ThemeContext,默认值为"light"。

2、在需要的位置使用Context的Provider

import ThemeContext from "./context/ThemeContext.js";import ThemedButton from "./ThemedButton.js";import "./App.css"; function App() {  return (          
);} export default App;

在组件的最外层使用了自定义Context的Provider,传入value覆盖了默认值,之后子组件读到的ThemeContext的值就是"dark"而不是默认值"light"。如果Provider有value定义就会使用value的值(即使值是undefined,即未传入value),只有当Provider未提供时才会使用定义时的默认值。

3、定义contextType,使用获取到的Context上的值

import React, { Component } from "react";import ThemeContext from "./context/ThemeContext.js"; class ThemedButton extends Component {static contextType = ThemeContext;render() {return ;}} export default ThemedButton;

ThemedButton声明了contextType是ThemeContext,因此this.context的值就是最近的ThemeContext提供的value,也就是"light"。

效果图:

推荐学习:《react视频教程》

以上就是react中context的用法是什么的详细内容,更多请关注php中文网其它相关文章!

关键词: 相关文章 一种新的 视频教程