千家信息网

Context-React如何跨组件访问数据

发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,这篇文章给大家分享的是有关Context-React如何跨组件访问数据的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。Context提供了一种跨组件访问数据的方法。它无需在组
千家信息网最后更新 2026年11月03日Context-React如何跨组件访问数据

这篇文章给大家分享的是有关Context-React如何跨组件访问数据的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。


  Context提供了一种跨组件访问数据的方法。它无需在组件树间逐层传递属性,也可以方便的访问其他组件的数据
  在经典的React应用中,数据是父组件通过props向子组件传递的。但是在某些特定场合,有些数据需要在各个组件之间共享。Context为我们提供一种组件之间共享数据的方式,可以避免数据在组件树上逐层传递
  使用Context的场合
Context可以在组件树的组件之间共享"全局"数据。例如:登陆的用户信息,用户选择的主题、语言等等。下面的例子中,我们"手动"自上而下传递theme属性,用来设定Button的样式。
class App extends React.Component {
render() {
return ;
}
}
function Toolbar(props) {
// The Toolbar component must take an extra "theme" prop
// and pass it to the ThemedButton. This can become painful
// if every single button in the app needs to know the theme
// because it would have to be passed through all components.
return (




);
}
class ThemedButton extends React.Component {
render() {
return ;
}
}
使用Context,我们可以避免通过多个中间组件传递props
// Context lets us pass a value deep into the component tree// without explicitly threading it through every component.// Create a context for the current theme (with "light" as the default).const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
// Use a Provider to pass the current theme to the tree below.
// Any component can read it, no matter how deep it is.
// In this example, we're passing "dark" as the current value.
return (



);
}
}

// A component in the middle doesn't have to
// pass the theme down explicitly anymore.
function Toolbar(props) {
return (




);
}

class ThemedButton extends React.Component {
// Assign a contextType to read the current theme context.
// React will find the closest theme Provider above and use its value.
// In this example, the current theme is "dark".
static contextType = ThemeContext;
render() {
return
)}

);
}

export default ThemeTogglerButton;
app.js
import {ThemeContext, themes} from './theme-context';import ThemeTogglerButton from './theme-toggler-button';
class App extends React.Component {
constructor(props) {
super(props);

this.toggleTheme = () => {  this.setState(state => ({    theme:      state.theme === themes.dark        ? themes.light        : themes.dark,  }));};// State also contains the updater function so it will// be passed down into the context providerthis.state = {  theme: themes.light,  toggleTheme: this.toggleTheme,};

}

render() {
// The entire state is passed to the provider
return (



);
}
}

function Content() {
return (




);
}

ReactDOM.render(, document.root);
使用多个Contexts
为了保持React的快速渲染,我们需要将每个consumer组件编写成一个独立的组件节点(node)
// Theme context, default to light themeconst ThemeContext = React.createContext('light');
// Signed-in user contextconst UserContext = React.createContext({
name: 'Guest',
});
class App extends React.Component {
render() {
const {signedInUser, theme} = this.props;

// App component that provides initial context valuesreturn (                  );

}
}

function Layout() {
return (





);
}

// A component may consume multiple contexts
function Content() {
return (

{theme => (

{user => (

)}

)}

);
}
如果有两个以上的context经常一起使用,我们需要考虑创建一个render prop component一并提供两个Context
注意
因为context使用引用标示符(reference identity)来判断何时需要重新渲染,所以有些情况下,当provider的父元素重新渲染时,会触发consumer的非内部渲染。例如下面代码,在每次Provider重新渲染时,会重新渲染所有的consumer组件。因为会一直创建一个新的对象赋值给value(value一直在变)
class App extends React.Component {
render() {
return (



);
}
}
为了避免这个问题,可以将value放在组件的state中
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: {something: 'something'},
};
}

render() {
return (



);
}
}

感谢各位的阅读!关于"Context-React如何跨组件访问数据"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

组件 数据 更新 函数 对象 代码 之间 多个 属性 元素 参数 后代 方式 方法 更多 监听 两个 信息 内容 场合 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 广州百单互联网科技有限公司 科技金融是不是互联网金融 科技平台互联网 鸠鸠互联网科技 互联网科技公司发展 智慧科技互联网 互联网科技公司名称 科技类的互联网平台 居家互联网科技有限公司 互联网巨头投资的硬核科技 承德科技产业互联网发展 南山科技园互联网公司有哪些 注册互联网科技公司经营范围大全 互联网科技和信息 西安小鹰速贷互联网科技有限公司 保险科技服务互联网营销体系 富国互联网金融科技混合基金 互联网相关科技技术 互联网高科技绘画 前海云享互联网科技 智慧科技互联网 互联网科技论坛 多迪互联网科技有限公司 中国互联网金融科技基金 深圳国际航运科技和互联网 创业天下互联网科技有限公司 恒生互联网科技业指数调整周期 上海钢联属于互联网科技股吗 下一代互联网重大应用科技园 平安好医生打造互联网科技医疗
0