[英]What is the way to correctly build toolbar with hamburger on react-native?
[英]What is the difference '<Toolbar />' and '{ Toolbar() }' in react render?
我發現在渲染中使用 '{ Toolbar() }' 時 useContext(ThemeContext) 的值不會更新。
react render 或 diff 中的 '' 和 '{ 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>
);
}
如果您將其稱為函數( ToolBar()
),則它本質上會返回其內容,因此不被視為 React 組件。 如果您使用<Toolbar />
,它就是一個組件,並且是正確的使用方式。
簡而言之,將其作為函數調用就像說“在此處打印此函數返回的任何內容”,而將其用作<Toolbar /
就像在說“在此處渲染此組件”。
函數調用將導致狀態、上下文或效果失敗,因此如果您不將該組件用作組件,則您的useContext
調用將不會產生預期的效果。
即使組件是功能組件,也不應直接將其用作函數。
React 包含了很多讓useContext
和朋友工作的魔法,但是當組件不用作組件時它不能這樣做。 如果您有興趣了解有關 React 背后機制的更多信息,以及為什么useContext
不起作用,請查看這篇文章。
在 ReactJS 中,您可以這樣調用組件:
<Component />
你像這樣調用函數:
{nameOfFunction()}
例如,如果您有任何常量,則打印其值:
const[value, setValue] = useState("Some Text...");
...
{value} // would pring Some Text...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.