如何使儿童与打字稿中的反应中呈现?
有点背景:我想在ReactJ中创建带有分页的组合旋转木马。
我有这样的代码:
interface HTMLCarouselT {
children: Array<JSX.Element>
size: number;
}
const HTMLCarousel = ({children, size}: HTMLCarouselT) => {
const length = Math.ceil(size / children.length);
const {
step,
isFirst,
isLast,
next: nextPage,
prev: prevPage
} = useStepper(length);
return (
<div>
<div>
{children.slice(step * size, size).map((Item, index) => (
<Item key={index}/>
))}
</div>
...
</div>
)
};
const App = () => {
return (
<HTMLCarousel size={3}>
<h1>One</h1>
<h1>Two</h1>
<h1>Three</h1>
<h1>Four</h1>
<h1>Five</h1>
<h1>Six</h1>
</HTMLCarousel>
);
}
但是我从打字稿中遇到了一个错误:
JSX元素类型“ item”没有任何构造或呼叫签名。
和运行时错误:
警告:react.Createelement:类型是无效的 - 期望字符串(用于内置组件)或类/函数(用于复合组件),但获取:
&lt; h1/&gt; 。您是否意外导出了JSX字面而不是组件?
在ReactJ和Typescript中展示儿童切片的正确方法是什么? 我希望我的组件能够普遍使用组件和元素。
A little background: I want to create a combination carousel with pagination in ReactJS.
I have code like this:
interface HTMLCarouselT {
children: Array<JSX.Element>
size: number;
}
const HTMLCarousel = ({children, size}: HTMLCarouselT) => {
const length = Math.ceil(size / children.length);
const {
step,
isFirst,
isLast,
next: nextPage,
prev: prevPage
} = useStepper(length);
return (
<div>
<div>
{children.slice(step * size, size).map((Item, index) => (
<Item key={index}/>
))}
</div>
...
</div>
)
};
const App = () => {
return (
<HTMLCarousel size={3}>
<h1>One</h1>
<h1>Two</h1>
<h1>Three</h1>
<h1>Four</h1>
<h1>Five</h1>
<h1>Six</h1>
</HTMLCarousel>
);
}
But I got an error from TypeScript:
JSX element type 'Item' does not have any construct or call signatures.
And runtime error:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got:
<h1 />
. Did you accidentally export a JSX literal instead of a component?
What is the proper way to display slices of children in ReactJS and TypeScript?
I want my component to be universal to work with components and elements.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
MAP
htmlcarousel
中,您已将当前元素引用为item
。在JSX中,您提到了
&lt; item&gt;
。它会导致搜索名为item
的组件。即使item
存在,由于当前元素变量也是item
,也将被忽略。TLDR:仅班级名称&amp;组件名称应从大写字母开始。
现在,要在地图中渲染孩子,只
要这样做就可以了。如果不替换
&lt; item&gt;
用&lt;&gt;
(react fragment)。In the
map
ofHTMLCarousel
you have referred to the current element asItem
.And in JSX, you have referred to
<Item>
. It causes React to search for a component namedItem
. Even ifItem
exists will be ignored due the current element variable also beingItem
.TLDR: Only class names & component names should begin with a capital letter.
Now to render children inside a map, just do
This should work. If not replace
<Item>
with<>
(React Fragment).