從 React 18 開始,我在渲染應用程式時遇到了一些錯誤,并且不能像看起來那樣嵌套任何元素。例如,我的應用程式中有以下代碼:
return (
<Card>
<div className={`flex flex-row justify-content-center align-items-center`}>
{props.icon}
<h2>{props.text}</h2>
</div>
<div className={"flex justify-content-center align-items-center"}>
<Button onClick={() => props.onButtonClick()} className={"w-2"} label={props.buttonText}/>
</div>
</Card>
);
此代碼在 React 18 之前運行良好,現在從 18 版本開始出現以下錯誤:

同樣,元素陣列也不能再被渲染,下面的代碼在 React17 中運行良好:
<DataTable metaKeySelection={false} selectionMode={"single"} onSelectionChange={e => {
setSelection(e.value)
}} selection={selection} stripedRows={true} showGridlines={true} size={"small"}
value={artifacts}>
{colModels}
</DataTable>
現在從 React18 開始出現以下問題:

在我看來,對于 v18,React 期望 React Nodes 無處不在,而 JSX 不再被接受。一旦我用 React 片段封裝所述元素,這些錯誤就會消失,這真的是解決這個問題的唯一方法嗎?
提前致謝!
uj5u.com熱心網友回復:
是的,React 18 確實做了一些更改,我不確定您的第二個問題,但您的第一個卡問題可以像這樣修復......
只需添加React Fragment 作為唯一的孩子<>。</>
<Card>
<>
<div className={`flex flex-row justify-content-center align-items-center`}>
{props.icon}
<h2>{props.text}</h2>
</div>
<div className={"flex justify-content-center align-items-center"}>
<Button onClick={() => props.onButtonClick()} className={"w-2"} label={props.buttonText}/>
</div>
</>
</Card>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482165.html
