加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – Typescript React,从无状态功能组件渲染数组

发布时间:2020-12-15 20:20:01 所属栏目:百科 来源:网络整理
导读:自React 16以来的React团队 announced: You can now return an array of elements from a component’s render method. 这适用于常规类组件的typescript,但我不能让它适用于无状态功能组件. 如果您想自己复制,请参阅this repo. 码: import * as React from
自React 16以来的React团队 announced:

You can now return an array of elements from a component’s render method.

这适用于常规类组件的typescript,但我不能让它适用于无状态功能组件.

如果您想自己复制,请参阅this repo.

码:

import * as React from 'react';

// See this example working in a non-TS environment: https://codesandbox.io/s/ppl3wopo8j
class Hello extends React.Component {
    render() {
        return <div>
        <Foo />
        <Bar /> {/* Error: 'JSX element type 'Element[]' is not a constructor function for JSX elements. */}
      </div>;
    }
}

class Foo extends React.Component {
    render() {
        return [<div>foo</div>,<div>fooz</div>];
    }
}

function Bar() {
    // Cannot render an array from a SFC
    return [<div>bar</div>,<div>baz</div>];
}

构建此snipper会导致以下错误:

'JSX element type 'Element[]' is not a constructor function for JSX elements.
  Property 'render' is missing in type 'Element[]'.'

如您所见,从常规类组件渲染数组有效,但在从无状态功能组件渲染数组时失败.

我不确定问题是我的代码/设置,DefinitelyTyped反应类型,还是打字稿本身.

解决方法

您可以通过将组件转换为任何组件来抑制错误并使代码工作:

const Bar: any = () => [<div>bar</div>,<div>baz</div>]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读