首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“<Toolbar/>”和“{ Toolbar() }”在react呈现中的区别是什么?

“<Toolbar/>”和“{ Toolbar() }”在react呈现中的区别是什么?
EN

Stack Overflow用户
提问于 2020-03-09 10:27:14
回答 3查看 57关注 0票数 2

我发现在呈现中使用'{ Toolbar() }‘时,useContext(ThemeContext)的值不是更新的。

“”和“{ Toolbar() }”在react、render或diff中有什么区别?

代码语言:javascript
复制
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>
  );
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-03-09 10:34:26

如果您调用它为一个函数(ToolBar()),它本质上返回它的内容,而不是这样的一个function组件。如果您使用<Toolbar />,那么它就是一个组件,也是正确的使用方法。

简而言之,将它作为一个函数调用就像说“在这里打印这个函数返回的东西”,使用它作为<Toolbar /就像说“在这里呈现这个组件”。

函数调用将导致状态、上下文或效果失败,因此如果不将组件用作组件,则useContext调用将不会产生预期的效果。

即使一个组件是一个功能组件,它也不应该直接用作一个函数。

React包含了很多让useContext和朋友工作的魔力,但是当组件没有被用作组件时,它就不能这么做了。如果您有兴趣了解更多关于反应背后的机制,以及为什么useContext不能工作的话,检查这篇文章

票数 0
EN

Stack Overflow用户

发布于 2020-03-09 10:40:35

在ReactJS中,您可以像这样调用组件:

代码语言:javascript
复制
<Component />

你这样称呼函数:

代码语言:javascript
复制
{nameOfFunction()}

例如,如果有任何常量,则打印其值:

代码语言:javascript
复制
const[value, setValue] = useState("Some Text...");

..。

代码语言:javascript
复制
{value} // would pring Some Text...
票数 0
EN

Stack Overflow用户

发布于 2020-03-09 10:41:27

<Toolbar />生成(通过JSX) [1] [2]

代码语言:javascript
复制
React.createElement(Toolbar, null)

Toolbar()是一个函数调用。

不要调用函数组件。渲染它们。

这就是为什么在呈现组件时需要使用JSX (或React.createElement),而不是简单地调用函数。通过这种方式,任何使用的钩子都可以在响应创建.的组件的实例中注册。

在您的示例中,useContext在调用博客文章中引用的Toolbar()时不会注册到组件的实例。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60598616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档