哪种语法对于这个泛型 TypeScript React 是正确的?

huangapple go评论100阅读模式
英文:

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&lt;T&gt;{
    items: T[];
    renderItem: (item: T) =&gt; ReactNode;
}

const List = &lt;T&gt;(props: ListProps&lt;T&gt;) =&gt; {
    return (
        &lt;div&gt;
            {props.items.map(props.renderItem)}
        &lt;/div&gt;
    );
};

I stacked with this functional component, how to write this generic &lt;T&gt; 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&lt;T&gt; {
  items: T[];
  renderItem: (item: T) =&gt; ReactNode;
}

const List: &lt;T&gt;(props: ListProps&lt;T&gt;) =&gt; ReactNode = props =&gt; {
  return &lt;div&gt;{props.items.map(props.renderItem)}&lt;/div&gt;;
};

Or if you choose to use function

interface ListProps&lt;T&gt; {
  items: T[];
  renderItem: (item: T) =&gt; ReactNode;
}

function List&lt;T&gt;(props: ListProps&lt;T&gt;) {
  return &lt;div&gt;{props.items.map(props.renderItem)}&lt;/div&gt;;
};

答案2

得分: 0

以下应该可以工作,注意带有逗号的&lt;T,&gt;。您可以参考这个很棒的答案获取更多信息。

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 &lt;T,&gt; with a comma. You can refer to this great answer for more information.

import * as React from &#39;react&#39;;

interface ListProps&lt;T&gt; {
    items: T[];
    renderItem: (item: T) =&gt; React.ReactNode;
}

const List = &lt;T,&gt;(props: ListProps&lt;T&gt;) =&gt; {
    return (
        &lt;div&gt;
            {props.items.map(props.renderItem)}
        &lt;/div&gt;
    );
};

huangapple
  • 本文由 发表于 2023年7月6日 20:08:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76628667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定