![](/img/trans.png)
[英]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.