React:设置 ReactNode 类型的状态会使应用程序崩溃

React: Setting a state of type ReactNode crashes the application

我想根据用户单击的内容动态呈现组件。我试过这样的事情:

function ComponentTest() {
    const [component, setComponent] = useState<ReactNode | null>(null);


    return <button onClick={() => setComponent(SomeFunctionalComponent)}>Crash</button>
}

在此示例中,我显然没有对状态进行任何操作,但单击此按钮会导致应用程序崩溃并显示以下错误消息:

Warning: Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks
Warning: React has detected a change in the order of Hooks called by EinstellungenTest. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks
Warning: Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks
Uncaught Error: Rendered more hooks than during the previous render.
The above error occurred in the <ComponentTest> component:

现在,我可以写

return <button onClick={() => setComponent(<SomeFunctionalComponent/>)}>Crash</button>

相反,但我认为创建组件太早了。我想在渲染期间创建组件,如下所示:

function ComponentTest() {
    const [component, setComponent] = useState<ReactNode | null>(null);


    return <component/>
}

我希望有人能帮我解决这个问题。

你可以在状态中保存你想使用的组件的值,然后使用条件渲染来渲染你想要的那个。

像这样

function ComponentTest() {
  const [componentId, setComponentId] = useState<string | null>(null);


    return <button onClick={() => setComponent("myId")}> {componentId === "myId" && < SomeFunctionalComponent  /> }</button>
}