在react中,context用于共享数据,并且允许数据隔代传递;context提供了一种新的组件之间共享数据的方式,不必显式地通过组件树的逐层传递props,能够避免使用大量重复的props来传递值。
本教程操作环境: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 ( <themecontext.provider value='dark'> <div classname="app"> <header classname="app-header"> <themedbutton /> </header> </div> </themecontext.provider> );} 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 <button>{this.context}</button>;}} export default themedbutton;
themedbutton声明了contexttype是themecontext,因此this.context的值就是最近的themecontext提供的value,也就是'light'。
效果图:
推荐学习:《react视频教程》
以上就是react中context的用法是什么的详细内容。