新版本react的context使用

栏目: 服务器 · 发布时间: 7年前

内容简介:Context 通过组件树提供了一个传递数据的方法,从而避免了在每一个层级手动的传递 props 属性。在一个典型的 React 应用中,数据是通过 props 属性由上向下(由父及子)的进行传递的,但这对于某些类型的属性而言是极其繁琐的(例如:地区偏好,UI主题),这是应用程序中许多组件都所需要的。 Context 提供了一种在组件之间共享此类值的方式,而不必通过组件树的每个层级显式地传递 props 。参考文档:

Context 通过组件树提供了一个传递数据的方法,从而避免了在每一个层级手动的传递 props 属性。

在一个典型的 React 应用中,数据是通过 props 属性由上向下(由父及子)的进行传递的,但这对于某些类型的属性而言是极其繁琐的(例如:地区偏好,UI主题),这是应用程序中许多组件都所需要的。 Context 提供了一种在组件之间共享此类值的方式,而不必通过组件树的每个层级显式地传递 props 。

参考文档: https://react.docschina.org/d...

connect.js

import React from 'react'
const ctx = React.createContext()
export const { Provider, Consumer } = ctx
export const withComponent = Component => props => <Consumer>{ propsObj => <Component { ...props } propsObj={propsObj}></Component> }</Consumer>
export default ctx

index.js

在最外层组件引入 Provider(*注意Provider的value名字不能改变)

import React, { Component } from 'react
import { Provider } from './connect.js
import Carder from './carder.js'
export default class Index extends Component {
    state = {
        test: false
    }
    render() {
        return (
            <Provider value={this.state.test}>
                <Carder>
            </Provider>
        )
    }
}

carder.js

import React, { Component } from 'react
import { withComponent } from './connect.js
class Carder extends Component {
    state = {
        test: false
    }
    render() {
        return (
            <div>
                <p>test的值为:{this.props.test}</p>
            </div>
        )
    }
}
export default withComponent(Carder )

以上所述就是小编给大家介绍的《新版本react的context使用》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Nine Algorithms That Changed the Future

Nine Algorithms That Changed the Future

John MacCormick / Princeton University Press / 2011-12-27 / GBP 19.95

Every day, we use our computers to perform remarkable feats. A simple web search picks out a handful of relevant needles from the world's biggest haystack: the billions of pages on the World Wide Web.......一起来看看 《Nine Algorithms That Changed the Future》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具