如何使用 React JS 和 Typescript 附加子自定义组件?

How to appendChild custom component using React JS and Typescript?

我有一些代码像

const ParentComponent = () => {
  let child = <ChildComponent {...props} />;
  if (condition) {
    const parent = document.GetElementById("parentId");
    //Here is a problem
    parent.appendChild(child);
  }
  return (
    <>
      <div id="parentId"></div>
    </>
  );
};
export default ParentComponent;

const ChildComponent = () => {
  return (
    <>
      <div></div>
    </>
  );
};
export default ChildComponent;

我想多次动态添加子组件却报错

我很乐意使用 Javascript 或 useRef 以任何方式做到这一点。 谢谢!

react中条件渲染的标准方式如下:

const ParentComponent = () => {
  return (
    <>
      <div id="parentId">
        {condition && <ChildComponent {...props } />}
      </div>
    </>
  );
};
export default ParentComponent;

您曾多次提到想要这样做,但没有举例说明您的想法。您可以创建一个数组并用您想要的任意数量的子元素填充它。例如:

const ParentComponent = () => {
  const [childCount, setChildCount] = useState(8);

  const children = [];
  for (let i = 0; i < childCount; i++) {
    if (condition) {
      children.push(<ChildComponent {...props } />);
    }
  }

  return (
    <>
      <div id="parentId">
        {children}
      </div>
    </>
  )
}