React中的context的用法和使用场景

时间:2020-05-29
本文章向大家介绍React中的context的用法和使用场景,主要包括React中的context的用法和使用场景使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用场景

如果你在组件间传递的数据逻辑比较复杂,可以使用reduex;

如果组件层级不多,可以使用props;

如果层级较深,数据逻辑简单,可以使用context。

以下是代码演示:

1.创建一个Context,const ThemeContext = React.createContext('light')

2.在父组件中用ThemeContext.Provider包裹子组件,用value传递数据

3.如果子组件是函数组件,要使用context时,需要用ThemeContext.Consumer包裹,通过value拿到数据;如果子组件是类组件,要使用context时,需要指定 contextType 读取当前的 theme context,这有两种方式,一种是在类组件中声明静态属性static contextType = ThemeContext,另一种是在组件外定义ThemedButton.contextType = ThemeContext,通过this.context拿到数据

import React from 'react'

// 创建 Context 填入默认值(任何一个 js 变量)
const ThemeContext = React.createContext('light')

// 底层组件 - 函数是组件
function ThemeLink(props) {
    // const theme = this.context // 会报错。函数式组件没有实例,即没有 this

    // 函数式组件可以使用 Consumer
    return <ThemeContext.Consumer>
        {value => <p>link's theme is {value}</p>}
    </ThemeContext.Consumer>
}

// 底层组件 - class 组件
class ThemedButton extends React.Component {
    // 指定 contextType 读取当前的 theme context。
    // static contextType = ThemeContext // 也可以用 ThemedButton.contextType = ThemeContext
    render() {
        const theme = this.context // React 会往上找到最近的 theme Provider,然后使用它的值。
        return <div>
            <p>button's theme is {theme}</p>
        </div>
    }
}
ThemedButton.contextType = ThemeContext // 指定 contextType 读取当前的 theme context。

// 中间的组件再也不必指明往下传递 theme 了。
function Toolbar(props) {
    return (
        <div>
            <ThemedButton />
            <ThemeLink />
        </div>
    )
}

class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            theme: 'light'
        }
    }
    render() {
        // 用Provider包起来
        return <ThemeContext.Provider value={this.state.theme}>
            <Toolbar />
            <hr />
            <button onClick={this.changeTheme}>change theme</button>
        </ThemeContext.Provider>
    }
    changeTheme = () => {
        this.setState({
            theme: this.state.theme === 'light' ? 'dark' : 'light'
        })
    }
}

export default App

原文地址:https://www.cnblogs.com/kewenxin/p/12988700.html