该功能实现效果类似于vue的provide/inject
而React可通过context
进行完成
定义一个公共的文件context/Theme.jsx
import { createContext } from 'react'; const theme = createContext() export default theme
父组件引入公共文件及子组件
并传递theme值
import React, { useState } from 'react'; import Child from "@/components/Child.jsx" import Theme from "@/context/Theme.jsx" export default () => { const [theme, setTheme] = useState("blue") return ( <> <button onClick={() => setTheme("green")}>检验context是否为响应式</button> <Theme.Provider value={theme}> <Child /> </Theme.Provider> </> ) }
子组件获取数据components/Child.jsx
import React from 'react'; import Theme from "@/context/Theme.jsx" export default () => { return ( <Theme.Consumer> {data => <p>接收父组件context传递的值:{data}</p>} </Theme.Consumer> ); }
到此这篇关于React通过conetxt实现多组件传值的文章就介绍到这了,更多相关React多组件传值内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!