首页 >

react中context的用法是什么

web前端|前端问答react中context的用法是什么
React
web前端-前端问答
混音算法源码,meteor+vscode,ubuntu 讲解,gc回收 tomcat,sqlite事务怎么解,wp响应式瀑布流插件,3个前端框架优缺点,爬虫能爬到片子嘛,php 高级 面试题,徐州seo优化套餐,手机网站源程序,网页分享摘要代码,化妆品营销型网站模板lzw
react中context的用法是什么
足球约战平台源码,ubuntu完善文件,用类写爬虫,promise php,google seo 词汇lzw
Context提供了一种新的组件之间共享数据的方式,允许数据隔代传递,而不必显式的通过组件树逐层传递props。
小学网站源码下载,如何降ubuntu版本,tomcat官网的cgi,爬虫time库,php ecb加密,渝北专业的seo优化怎么样lzw
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中context的用法是什么

《react视频教学》


  • 暂无相关文章
  • Posted in 未分类