九州編程
2022-05-14 13:42:04
我發現在渲染中使用“{ Toolbar()}”時,useContext(ThemeContext) 的值沒有更新。反應渲染或差異中的''和'{ Toolbar()}'有什么區別?import React, { useContext, useState } from "react";import "./styles.css";const themes = { light: { name: "light", foreground: "black", background: "white" }, dark: { name: "dark", foreground: "white", background: "black" }};const ThemeContext = React.createContext(null);const Toolbar = props => { const theme = useContext(ThemeContext) || {}; console.log(`Toolbar theme`, theme); return ( <div style={{ height: 60, backgroundColor: theme.background, color: theme.foreground }} > <div>{theme.name}</div> </div> );};export default function App() { const [currentTheme, setCurrentTheme] = useState(themes.light); const toggleTheme = theme => { setCurrentTheme(theme); }; console.log(`currentTheme`, currentTheme); return ( <div className="App"> <ThemeContext.Provider value={currentTheme}> <div> <button onClick={() => toggleTheme(themes.light)}>light</button> <button onClick={() => toggleTheme(themes.dark)}>dark</button> </div> {/* Toolbar() */} {/* {Toolbar()} */} <Toolbar /> </ThemeContext.Provider> </div> );}
3 回答

嚕嚕噠
TA貢獻1784條經驗 獲得超7個贊
如果您將其作為函數 ( ToolBar()
) 調用,它本質上會返回其內容,因此不被視為 React 組件。如果您使用<Toolbar />
,它是一個組件,并且是使用它的正確方法。
簡而言之,將其作為函數調用就像是說“在此處打印此函數返回的任何內容”,而使用它就像是<Toolbar /
在說“在此處渲染此組件”。
函數調用將導致狀態、上下文或效果失敗,因此useContext
如果您不將組件用作組件,您的調用將不會產生預期的效果。
即使組件是功能組件,也不應該直接作為功能使用。
React 包含很多可以擁有的魔法useContext
和可以工作的朋友,但是當組件不作為組件使用時,它就無法做到這一點。如果你有興趣了解更多關于 React 背后的機制,以及為什么useContext
不工作,請查看這篇文章。

一只萌萌小番薯
TA貢獻1795條經驗 獲得超7個贊
在 ReactJS 中,你可以這樣調用組件:
<Component />
你這樣調用函數:
{nameOfFunction()}
例如,如果您有任何常量,則打印其值:
const[value, setValue] = useState("Some Text...");
...
{value} // would pring Some Text...

當年話下
TA貢獻1890條經驗 獲得超9個贊
React.createElement(Toolbar, null)
WhileToolbar()
是一個函數調用。
這就是為什么在渲染組件時需要使用 JSX(或 React.createElement)而不是簡單地調用函數的原因。這樣,任何使用的鉤子都可以注冊到 React 創建的組件的實例中。
在您的示例中,useContext
不會Toolbar()
像博客文章中引用的那樣在調用時注冊到組件的實例。
添加回答
舉報
0/150
提交
取消