gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:53:10 24 4
gpt4 key购买 nike

React 团队 announced自 React 16 以来:

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 react 类型还是 typescript 本身。

最佳答案

直到打开Definitely Typed问题已解决,最好的解决方法可能就是使用 <React.Fragment/>反而。出于功能目的,我认为没有任何区别:

const Bar: React.SFC<CheckoutProps> = (props) => {
return (
<React.Fragment>
<div>bar</div>
<div>baz</div>
</React.Fragment>
);
};

关于reactjs - Typescript + React,从无状态功能组件渲染数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46709773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com