维护React组件列表,然后渲染到父组件中。

问题描述 投票:2回答:1

我有一个关于维护一个多态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>);
    };
};

GenericBlock.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但我认为它抓住了我所说的精神。有什么方法可以让上面的方案正常工作吗?

我确信这个问题已经有人问过了,也有人回答过了,但我似乎无法让谷歌搜索正确。

EDIT:

添加了沙盒链接。https:/codesandbox.ioswizardly-wilson-vb7nn。

现在我遇到了一个新的错误。Type 'Element' is missing the following properties from type 'GenericBlock': render, context, setState, forceUpdate, and 2 more.

EDIT 2:

打字: blocks 数组作为JSX.Element删除了错误,并使一切工作,但这似乎不是很好的做法,因为 JSX.Element 可以是任何元素,而将它打成 GenericBlock 是为了确保所有的元素都是一个特定组件的后裔。

reactjs typescript
1个回答
3
投票

在React代码中,它完美地工作。https:/codesandbox.iosoptimistic -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"
  }
© www.soinside.com 2019 - 2024. All rights reserved.