【问题标题】:React Invalid Hook Call Error with useState In Functional Component使用功能组件中的 useState 反应无效的挂钩调用错误
【发布时间】:2021-06-24 21:41:13
【问题描述】:

我按照here 发现的无效钩子警告无济于事。我在代码中忽略了一些错误。当我使用命令 npm ls react-dom 我得到:“react-dom@17.0.2”。我的代码有什么问题?我认为您可以像下面那样在功能组件中使用 useState 钩子

import {useState} from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function Navbar()
{
  const [childFontSize, setChildFontSize] = useState("5vh"); 

  return(
    <div id={"navbarContainer"}> 
      <span className={"font"}>XYZ</span>
      <span className={"font"} style={{fontSize: childFontSize}}>XYZ</span>
      <span className={"font"} style={{fontSize: childFontSize}}>XYZ</span>
      <span className={"font"} style={{fontSize: childFontSize}}>XYZ</span>
    </div>
  );
}

ReactDOM.render(Navbar(), document.getElementById("navbar"));

【问题讨论】:

  • 这是用于浏览器的 React 还是 React Native? ReactDOM 仅用于浏览器,但您添加了 react-native 标签

标签: javascript reactjs react-native react-hooks


【解决方案1】:

问题出在这一行:

ReactDOM.render(Navbar(), document.getElementById("navbar"));

函数式组件永远不应该作为函数调用,它们需要使用 JSX 或 React.createElement 调用。

ReactDOM.render(<Navbar />, document.getElementById("navbar"));

或者(不要这样做)你可以调用 React.createElement(这是 JSX 被编译成的):https://reactgo.com/react-createelement-example/

ReactDOM.render(React.createElement(Navbar, null, null), document.getElementById("navbar"));

// not on StackOverflow
// import {useState} from 'react';
// import ReactDOM from 'react-dom';
// import './index.css';

const useState = React.useState;

function Navbar()
{
  const [childFontSize, setChildFontSize] = useState("5vh"); 

  return(
    <div id={"navbarContainer"}> 
      <span className={"font"}>XYZ</span>
      <span className={"font"} style={{fontSize: childFontSize}}>XYZ</span>
      <span className={"font"} style={{fontSize: childFontSize}}>XYZ</span>
      <span className={"font"} style={{fontSize: childFontSize}}>XYZ</span>
    </div>
  );
}

ReactDOM.render(<Navbar />, document.getElementById("navbar"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="navbar"></div>

【讨论】:

  • 非常感谢! 围绕功能组件名称的解决方案奏效了!
猜你喜欢
  • 1970-01-01
  • 2023-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
  • 1970-01-01
相关资源
最近更新 更多