繁体   English   中英

有什么不同 &#39;<Toolbar /> &#39; 和 &#39;{ Toolbar() }&#39; 在反应渲染中?

[英]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...

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

React.createElement(Toolbar, null)

Toolbar()是一个函数调用。

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

这就是为什么在渲染组件时需要使用 JSX(或 React.createElement)而不是简单地调用函数的原因。 这样,任何使用的钩子都可以注册到 React 创建的组件实例。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM