打字稿+反应,从一个无状态的功能组件
问题描述:
渲染阵列中的阵营团队announced,自阵营16:打字稿+反应,从一个无状态的功能组件
You can now return an array of elements from a component’s render method.
这适用于打字稿定期类组件,但我不能让它无状态的功能工作组件。
请参阅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>];
}
建设这个剪断导致以下错误:
'JSX element type 'Element[]' is not a constructor function for JSX elements.
Property 'render' is missing in type 'Element[]'.'
正如你所看到的,从一个普通类组件的工作原理渲染阵列,但渲染时失败来自无状态功能组件的数组。
我不确定问题出在我的代码/设置,DefinitelyTyped反应类型还是与打字稿本身。
答
“您现在可以从组件的渲染方法中返回一组元素。”
JSX数组正在编译React.Components render方法。无状态的功能组件缺少该渲染方法。
您可以将您的元素数组包装在父div中而不是数组中或使用常规类组件。
答
您可以取消错误,让你的代码工作铸造你的组件作为any
:
const Bar: any =() => [<div>bar</div>, <div>baz</div>]
号可以返回甚至无状态的功能组件阵列。请参阅示例:https://codepen.io/pawelgrzybek/pen/WZEKWj – Dane
感谢您的注意。看起来这是一个类型错误。 –