英文:
Which syntax is correct for this generic TypeScript React
问题
我的组件应该对列表进行映射,其中所有元素都是相同类型。在props中,我传递列表和返回JSX元素的函数。
interface ListProps<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
const List = <T>(props: ListProps<T>) => {
return (
<div>
{props.items.map(props.renderItem)}
</div>
);
};
我对这个泛型<T>
的函数式组件感到困惑,如何正确地编写它?
英文:
My component should map through a list where all elements are same type. In props I give list and function which returns JSX element
interface ListProps<T>{
items: T[];
renderItem: (item: T) => ReactNode;
}
const List = <T>(props: ListProps<T>) => {
return (
<div>
{props.items.map(props.renderItem)}
</div>
);
};
I stacked with this functional component, how to write this generic <T>
properly?
答案1
得分: 1
你应该按照以下方式创建你的类型:
interface ListProps<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
const List: <T>(props: ListProps<T>) => ReactNode = props => {
return <div>{props.items.map(props.renderItem)}</div>;
};
或者,如果你选择使用函数:
interface ListProps<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
function List<T>(props: ListProps<T>) {
return <div>{props.items.map(props.renderItem)}</div>;
};
英文:
You should create your type as follows
interface ListProps<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
const List: <T>(props: ListProps<T>) => ReactNode = props => {
return <div>{props.items.map(props.renderItem)}</div>;
};
Or if you choose to use function
interface ListProps<T> {
items: T[];
renderItem: (item: T) => ReactNode;
}
function List<T>(props: ListProps<T>) {
return <div>{props.items.map(props.renderItem)}</div>;
};
答案2
得分: 0
以下应该可以工作,注意带有逗号的<T,>
。您可以参考这个很棒的答案获取更多信息。
import * as React from 'react';
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
const List = <T>(props: ListProps<T>) => {
return (
<div>
{props.items.map(props.renderItem)}
</div>
);
};
英文:
The following should work, note the <T,>
with a comma. You can refer to this great answer for more information.
import * as React from 'react';
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
const List = <T,>(props: ListProps<T>) => {
return (
<div>
{props.items.map(props.renderItem)}
</div>
);
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论