React的类组件和函数组件context使用以及Hook中useContext使用

1、类组件使用context

使用流程:

  • 生产
  • 消费
import React, { useContext } 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>

    // 函数组件引入context也是可以的,那就意味这两种消费方式都可以
    const theme = useContext(ThemeContext);
    return <p>link's theme333333 is {theme}</p>
}

// 底层组件 - 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 ContextDemo extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            theme: 'light'
        }
    }
    render() {
        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 ContextDemo



2、函数组件使用context

import React, { useContext } from 'react'

// 主题颜色
const themes = {
    light: {
        foreground: '#000',
        background: '#eee'
    },
    dark: {
        foreground: '#fff',
        background: '#222'
    }
}

// 创建 Context
const ThemeContext = React.createContext(themes.light) // 初始值

function ThemeButton() {
    const theme = useContext(ThemeContext)

    return <button style={{ background: theme.background, color: theme.foreground }}>
        hello world
    </button>
}

function Toolbar() {
    return <div>
        <ThemeButton></ThemeButton>
    </div>
}

function App() {
    return <ThemeContext.Provider value={themes.dark}>
        <Toolbar></Toolbar>
    </ThemeContext.Provider>
}

export default App

3、Hook中useContext的使用

import React, { useContext } from "react";
import ReactDOM from "react-dom";

const TestContext= React.createContext({});

const Navbar = () => {
  const { username } = useContext(TestContext)

  return (
    <div className="navbar">
      <p>{username}</p>
    </div>
  )
}

const Messages = () => {
  const { username } = useContext(TestContext)

  return (
    <div className="messages">
      <p>1 message for {username}</p>
    </div>
  )
}

function App() {
  return (
	<TestContext.Provider 
		value={{
			username: 'superawesome',
		}}
	>
		<div className="test">
			<Navbar />
			<Messages />
		</div>
	<TestContext.Provider/>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React Hook,子组件调用父组件函数的几种方法如下: 1. 通过props传递函数,子组件调用该函数实现调用父组件函数。 父组件代码: ```javascript import React from 'react'; import Child from './Child'; const Parent = () => { const handleClick = () => { console.log('Parent function called'); }; return ( <div> <Child handleClick={handleClick} /> </div> ); }; export default Parent;``` 子组件代码: ```javascript import React from 'react'; const Child = ({ handleClick }) => { const handleChildClick = () => { handleClick(); }; return ( <div> <button onClick={handleChildClick}>Call Parent Function</button> </div> ); }; export default Child; ``` 2. 使用useRef创建一个ref实例,并将其赋值给shareRef变量。通过指定ref为JSX属性,将其向下传递给子组件。子组件通过forwardRef获取父组件传递的ref,并使用useImperativeHandle将需要暴露给父组件函数暴露出来。 父组件代码: ```javascript import React, { useRef } from 'react'; import Child from './Child'; const Parent = () => { const shareRef = useRef(); const handleParentClick = () => { shareRef.current.handleChildClick(); }; return ( <div> <button onClick={handleParentClick}>Call Child Function</button> <Child ref={shareRef} /> </div> ); }; export default Parent; ``` 子组件代码: ```javascript import React, { forwardRef, useImperativeHandle } from 'react'; const Child = forwardRef((props, ref) => { useImperativeHandle(ref, () => ({ handleChildClick: () => { console.log('Child function called'); }, })); return <div>Child Component</div>; }); export default Child; ``` 3. 使用Context API,将父组件函数通过Context传递给子组件,子组件通过useContext获取父组件传递的函数并调用。 父组件代码: ```javascript import React, { createContext } from 'react'; import Child from './Child'; export const MyContext = createContext(); const Parent = () => { const handleClick = () => { console.log('Parent function called'); }; return ( <MyContext.Provider value={handleClick}> <Child /> </MyContext.Provider> ); }; export default Parent; ``` 子组件代码: ```javascript import React, { useContext } from 'react'; import { MyContext } from './Parent'; const Child = () => { const handleClick = useContext(MyContext); const handleChildClick = () => { handleClick(); }; return ( <div> <button onClick={handleChildClick}>Call Parent Function</button> </div> ); }; export default Child; ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值