我有一些代碼像
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 以任何方式完成它。謝謝!
uj5u.com熱心網友回復:
在 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>
</>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/369359.html
標籤:javascript 反应 dom jsx
