学习react-Provider解决props需要层层传递问题

1.组件数据传递问题

数据传递:A(顶级组件)-》B组件(子组件)、C组件(孙子组件)…很多组件
这样得通过props层层传递到下面的组件
还有另一种解决方法,即通过全局对象来解决,使用Provider可以解决数据层层传递和每个组件都要传props的问题;

2.props传递例子

学习react-环境&手脚架&页面&路由
在上一节的路由配置文件中,HomePage传递了name值

// Router.tsx
const routes: RouteObject[] = [
    {
   
        path: '/',
        element:<HomePage name={
   "test"} /> //<Navigate to='home/one' /> // 重定向
    },
    {
   
        path: 'login',
        element: <LoginPage name={
   "login"} />
    },
    // 未匹配到页面
    {
   
        path: '*',
        element: <NotFoundPage name={
   "notfound"} />
    }
]

在这一节中,创建MainPage,并在HomePage中引用

// MainMeta.tsx
export interface MainProp extends MetaProp{
   
    
}

export interface MainState extends MetaState{
   
   
}
// MainPage.tsx
class MainPage extends Component<MainProp, MainState> {
   
    constructor(props: MainProp) {
   
        super(props);
        this.state = {
    count: 0 };
     }

    render() {
   
        const {
    name } = this.props; //解构赋值
      return <h1>Hello main page, {
   name}!</h1>;
    }
  }

MainPage在HomePage中引用,并用props继续给MainPage传递name值

// MainPage.tsx
class MainPage extends Component<MainProp, MainState> {
   
    constructor(props: MainProp) {
   
        super(props);
        this.state = {
    count: 0 };
     }

    render() {
   
        const {
    name } = this.props; //解构赋值
      return <h1>Hello main page, {
   name}!</h1>;
    }
  }

如下图props的name字段,值为test,一层层传递
props的name字段,值为test, 一层层传递

3.用全局对象context

1. state共同维护context(function模式)

首先创造Global.tsx和ConfigProvider.tsx

// Global.tsx
class Global {
   
    constructor() {
   
    }
    count = 0;
    name = 'react';
    loading =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值