在此反应组件中
useState
在嵌套函数a内被调用。为什么这是有效的,因为钩子不能位于嵌套函数内部?
import { useState } from "react";
export function App() {
let a = () => {
const [color, setColor] = useState("hellojo");
return color;
};
let b = a();
return (
<div className="App">
{b}
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Hooks 需要在组件声明的顶层声明。在 React 中声明组件的正确方法是给它一个 PascalCase 名称并返回一些 JSX。
尝试这样写:
export function App() {
const ColorComponent = () => {
// eslint-disable-next-line no-unused-vars
const [color, setColor] = useState("hellojo");
return color;
};
const b = <ColorComponent />;
return (
<div className="App">
{b}
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
或者将组件移动到自己的文件中:
// ColorComponent.jsx
const ColorComponent = () => {
// eslint-disable-next-line no-unused-vars
const [color, setColor] = useState("hellojo");
return color;
};
export default ColorComponent;
并将其导入您的
App.jsx
。