亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

反應渲染中的“<Toolbar />”和“{ Toolbar() }”有什么區別?

反應渲染中的“<Toolbar />”和“{ Toolbar() }”有什么區別?

九州編程 2022-05-14 13:42:04
我發現在渲染中使用“{ Toolbar()}”時,useContext(ThemeContext) 的值沒有更新。反應渲染或差異中的''和'{ 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>  );}
查看完整描述

3 回答

?
嚕嚕噠

TA貢獻1784條經驗 獲得超7個贊

如果您將其作為函數 ( ToolBar()) 調用,它本質上會返回其內容,因此不被視為 React 組件。如果您使用<Toolbar />,它是一個組件,并且是使用它的正確方法。

簡而言之,將其作為函數調用就像是說“在此處打印此函數返回的任何內容”,而使用它就像是<Toolbar /在說“在此處渲染此組件”。

函數調用將導致狀態、上下文或效果失敗,因此useContext如果您不將組件用作組件,您的調用將不會產生預期的效果。

即使組件是功能組件,也不應該直接作為功能使用。

React 包含很多可以擁有的魔法useContext和可以工作的朋友,但是當組件不作為組件使用時,它就無法做到這一點。如果你有興趣了解更多關于 React 背后的機制,以及為什么useContext不工作,請查看這篇文章。


查看完整回答
反對 回復 2022-05-14
?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

在 ReactJS 中,你可以這樣調用組件:

<Component />

你這樣調用函數:

{nameOfFunction()}

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

const[value, setValue] = useState("Some Text...");

...

{value} // would pring Some Text...


查看完整回答
反對 回復 2022-05-14
?
當年話下

TA貢獻1890條經驗 獲得超9個贊

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

React.createElement(Toolbar, null)

WhileToolbar()是一個函數調用。

不要調用函數組件。渲染它們。

這就是為什么在渲染組件時需要使用 JSX(或 React.createElement)而不是簡單地調用函數的原因。這樣,任何使用的鉤子都可以注冊到 React 創建的組件的實例中。

在您的示例中,useContext不會Toolbar()像博客文章中引用的那樣在調用時注冊到組件的實例。


查看完整回答
反對 回復 2022-05-14
  • 3 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號