如何在React JS与Typescript中动态添加自定义子组件?
错误原因
你的代码存在两个核心问题导致报错:
child变量存储的是React虚拟DOM元素,不是浏览器原生DOM节点,而appendChild方法仅支持传入原生DOM对象,会抛出类型不匹配错误- 直接在组件渲染逻辑中调用
document.getElementById可能获取不到目标节点,此时JSX还未挂载到真实DOM树,拿到的值为null,调用appendChild会直接报错
推荐实现方案(符合React设计理念,无需手动操作DOM)
通过状态管理子组件列表,需要添加子组件时修改状态即可,React会自动完成渲染更新:
import { useState } from 'react'; const ChildComponent = () => { return ( <> <div>子组件内容</div> </> ); }; const ParentComponent = (props) => { // 状态存储子组件的配置列表,支持为每个子组件传入独立props const [childList, setChildList] = useState([]); // 调用此方法即可新增子组件,可绑定到点击、条件判断等任意触发逻辑 const addChild = () => { setChildList(prev => [...prev, { uniqueId: Date.now() }]); }; return ( <> <button onClick={addChild}>添加子组件</button> <div id="parentId"> {childList.map(item => ( <ChildComponent key={item.uniqueId} {...props} /> ))} </div> </> ); }; export default ParentComponent;
可选方案(特殊场景需手动操作DOM时使用)
如果确实有需求直接操作DOM节点,可通过useRef获取父容器,配合createRoot渲染React组件到指定DOM:
import { useRef } from 'react'; import { createRoot } from 'react-dom/client'; const ChildComponent = () => { return ( <> <div>子组件内容</div> </> ); }; const ParentComponent = (props) => { const parentRef = useRef(null); const addChild = () => { if (!parentRef.current) return; // 创建原生DOM容器 const childContainer = document.createElement('div'); parentRef.current.appendChild(childContainer); // 渲染React组件到原生容器 const root = createRoot(childContainer); root.render(<ChildComponent {...props} />); }; return ( <> <button onClick={addChild}>添加子组件</button> <div ref={parentRef} id="parentId"></div> </> ); }; export default ParentComponent;
内容的提问来源于stack exchange,提问作者Tuvia Khusid
相关产品推荐
相关产品推荐

