[英]Maintaining a List of React Components then rendering into parent
我有一個關於維護多態 React 組件數組的假設問題。 是否有可能/良好的 React 實踐來維護作為公共組件后代的組件數組,然后在容器中呈現它們? 例如:
import * as React from 'react';
import GenericBlock from './GenericBlock';
import { BlockTypeA, BlockTypeB, BlockTypeC } from './MyBlocks';
export default class BlockHolder extends React.Component {
blocks : GenericBlock[] = [ <BlockTypeA />, <BlockTypeB />, <BlockTypeC /> ];
render() {
return (
<div id="workspace">
{
this.blocks
}
</div>);
};
};
通用塊.tsx
import * as React from 'react';
export default class GenericBlock extends React.Component {
render() { return (<div></div>); }
}
MyBlocks.tsx:
import * as React from 'react';
import GenericBlock from './GenericBlock';
class BlockTypeA extends GenericBlock {
render() { return (<div></div>); }
};
class BlockTypeB extends GenericBlock {
render() { return (<div></div>); }
};
class BlockTypeC extends GenericBlock {
render() { return (<div></div>); }
};
export { BlockTypeA, BlockTypeB, BlockTypeC };
上面的代碼片段產生了錯誤: Objects are not valid as a React child
,但我認為它抓住了我所說的精神。 有沒有辦法使上述方案奏效?
我確信已經提出並回答了這個問題,但我似乎無法讓 Google 搜索正確。
編輯:
添加沙盒鏈接: https://codesandbox.io/s/wizardly-wilson-vb7nn
現在我遇到了一個新錯誤: Type 'Element' is missing the following properties from type 'GenericBlock': render, context, setState, forceUpdate, and 2 more.
編輯 2 :
將blocks
數組鍵入為 JSX.Element 可以消除錯誤並使一切正常,但這似乎不是很好的做法,因為JSX.Element
可以是任何元素,而將其鍵入為GenericBlock
的目的是確保所有元素是特定組件的后代。
在反應代碼中,它完美地工作: https://codesandbox.io/s/optimistic-ptolemy-g25ge
沒有錯誤,沒有警告
import * as React from "react";
import { BlockTypeA, BlockTypeB, BlockTypeC } from "./MyBlocks";
export default class BlockHolder extends React.Component {
blocks = [
<BlockTypeA key={1} />,
<BlockTypeB key={2} />,
<BlockTypeC key={3} />
];
render() {
return <div id="workspace">{this.blocks}</div>;
}
}
import * as React from "react";
export default class GenericBlock extends React.Component {
render() {
return <div />;
}
}
import * as React from 'react';
import GenericBlock from './GenericBlock';
class BlockTypeA extends GenericBlock {
render() { return (<div>A</div>); }
};
class BlockTypeB extends GenericBlock {
render() { return (<div>B</div>); }
};
class BlockTypeC extends GenericBlock {
render() { return (<div>C</div>); }
};
export { BlockTypeA, BlockTypeB, BlockTypeC };
"dependencies": {
"react": "16.12.0",
"react-dom": "16.12.0",
"react-scripts": "3.0.1"
},
"devDependencies": {
"typescript": "3.8.3"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.