簡體   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