Introduction
Yay! ? You've made it to the final part of this two-part series! If you haven't already checked out Part 1, stop right here and go through that first. Don't worry, we'll wait until you’re back! ?
In Part 1, we built the CustomTable component. You can see it in action here.
In this second part, we’ll be extending the component to add some new features. Here's what we'll be working towards:
To support this, the CustomTable component will need some enhancements:
- The ability to format the rendered value—e.g., rendering a number with proper formatting.
- Flexibility to allow users to provide custom templates for rendering rows, giving them control over how each column is displayed.
Let's dive into building the first feature.
Extending the Column Interface
We’ll start by adding a format method to the Column interface to control how specific columns render their values.
interface Column<t> { id: keyof T; label: string; format?: (value: string | number) => string; } </t>
This optional format method will be used to format data when necessary. Let’s see how this works with an example from the Country.tsx file. We’ll add a format method to the population column.
const columns: Column<country>[] = [ { id: "name", label: "Name" }, { id: "code", label: "ISO\u00a0Code" }, { id: "population", label: "Population", format: (value) => new Intl.NumberFormat("en-US").format(value as number), }, { id: "size", label: "Size\u00a0(km\u00b2)", }, { id: "density", label: "Density", }, ]; </country>
Here, we’re using the JavaScript Intl.NumberFormat method to format the population as a number. You can learn more about this method here.
Next, we need to update our CustomTable component to check for the format function and apply it when it exists.
<tablebody> {rows.map((row, index) => ( <tablerow hover tabindex="{-1}" key="{index}"> {columns.map((column, index) => ( <tablecell key="{index}"> {column.format ? column.format(row[column.id] as string) : (row[column.id] as string)} </tablecell> ))} </tablerow> ))} </tablebody>
With this modification, the population column now renders with the appropriate formatting. You can see it in action here.
Supporting Custom Templates
Now, let's implement the next feature: allowing custom templates for rendering columns. To do this, we’ll add support for passing JSX as a children prop or using render props, giving consumers full control over how each cell is rendered.
First, we’ll extend the Props interface to include an optional children prop.
interface Props<t> { rows: T[]; columns: Column<t>[]; children?: (row: T, column: Column<t>) => React.ReactNode; } </t></t></t>
Next, we’ll modify our CustomTable component to support this new prop while preserving the existing behavior.
<tablerow> {columns.map((column, index) => ( <tablecell key="{index}"> {children ? children(row, column) : column.format ? column.format(row[column.id] as string) : row[column.id]} </tablecell> ))} </tablerow>
This ensures that if the children prop is passed, the custom template is used; otherwise, we fall back to the default behavior.
Let’s also refactor the code to make it more reusable:
const getFormattedValue = (column, row) => { const value = row[column.id]; return column.format ? column.format(value) : value as string; }; const getRowTemplate = (row, column, children) => { return children ? children(row, column) : getFormattedValue(column, row); };
Custom Row Component
Now let’s build a custom row component in the Countries.tsx file. We’ll create a CustomRow component to handle special rendering logic.
interface RowProps { row: Country; column: Column<country>; } const CustomRow = ({ row, column }: RowProps) => { const value = row[column.id]; if (column.format) { return <span>{column.format(value as string)}</span>; } return <span>{value}</span>; }; </country>
Then, we’ll update Countries.tsx to pass this CustomRow component to CustomTable.
const Countries = () => ( <customtable columns="{columns}" rows="{rows}"> {(row, column) => <customrow column="{column}" row="{row}"></customrow>} </customtable> );
For People.tsx, which doesn’t need any special templates, we can simply render the table without the children prop.
const People = () => <customtable columns="{columns}" rows="{rows}"></customtable>;
Improvements
One improvement we can make is the use of array indexes as keys, which can cause issues. Instead, let’s enforce the use of a unique rowKey for each row.
We’ll extend the Props interface to require a rowKey.
interface Props<t> { rowKey: keyof T; rows: T[]; columns: Column<t>[]; children?: (row: T, column: Column<t>) => React.JSX.Element | string; onRowClick?: (row: T) => void; } </t></t></t>
Now, each consumer of CustomTable must provide a rowKey to ensure stable rendering.
<customtable rowkey="code" rows="{rows}" onrowclick="{handleRowClick}" columns="{columns}"> {(row, column) => <customrow column="{column}" row="{row}"></customrow>} </customtable>
Final Code
Check out the full code here.
Conclusion
In this article, we extended our custom CustomTable component by adding formatting options and the ability to pass custom templates for columns. These features give us greater control over how data is rendered in tables, while also making the component flexible and reusable for different use cases.
We also improved the component by enforcing a rowKey prop to avoid using array indexes as keys, ensuring more efficient and stable rendering.
I hope you found this guide helpful! Feel free to share your thoughts in the comments section.
Thanks for sticking with me through this journey! ?
以上がReact と Typescript を使用してカスタム テーブル コンポーネントを作成する方法 (パート 2)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

JavaScriptコアデータ型は、ブラウザとnode.jsで一貫していますが、余分なタイプとは異なる方法で処理されます。 1)グローバルオブジェクトはブラウザのウィンドウであり、node.jsのグローバルです2)バイナリデータの処理に使用されるNode.jsの一意のバッファオブジェクト。 3)パフォーマンスと時間の処理にも違いがあり、環境に従ってコードを調整する必要があります。

javascriptusestwotypesofcomments:シングルライン(//)およびマルチライン(//)

PythonとJavaScriptの主な違いは、タイプシステムとアプリケーションシナリオです。 1。Pythonは、科学的コンピューティングとデータ分析に適した動的タイプを使用します。 2。JavaScriptは弱いタイプを採用し、フロントエンドとフルスタックの開発で広く使用されています。この2つは、非同期プログラミングとパフォーマンスの最適化に独自の利点があり、選択する際にプロジェクトの要件に従って決定する必要があります。

PythonまたはJavaScriptを選択するかどうかは、プロジェクトの種類によって異なります。1)データサイエンスおよび自動化タスクのPythonを選択します。 2)フロントエンドとフルスタック開発のためにJavaScriptを選択します。 Pythonは、データ処理と自動化における強力なライブラリに好まれていますが、JavaScriptはWebインタラクションとフルスタック開発の利点に不可欠です。

PythonとJavaScriptにはそれぞれ独自の利点があり、選択はプロジェクトのニーズと個人的な好みに依存します。 1. Pythonは、データサイエンスやバックエンド開発に適した簡潔な構文を備えた学習が簡単ですが、実行速度が遅くなっています。 2。JavaScriptはフロントエンド開発のいたるところにあり、強力な非同期プログラミング機能を備えています。 node.jsはフルスタックの開発に適していますが、構文は複雑でエラーが発生しやすい場合があります。

javascriptisnotbuiltoncorc;それは、解釈されていることを解釈しました。

JavaScriptは、フロントエンドおよびバックエンド開発に使用できます。フロントエンドは、DOM操作を介してユーザーエクスペリエンスを強化し、バックエンドはnode.jsを介してサーバータスクを処理することを処理します。 1.フロントエンドの例:Webページテキストのコンテンツを変更します。 2。バックエンドの例:node.jsサーバーを作成します。

PythonまたはJavaScriptの選択は、キャリア開発、学習曲線、エコシステムに基づいている必要があります。1)キャリア開発:Pythonはデータサイエンスとバックエンド開発に適していますが、JavaScriptはフロントエンドおよびフルスタック開発に適しています。 2)学習曲線:Python構文は簡潔で初心者に適しています。 JavaScriptの構文は柔軟です。 3)エコシステム:Pythonには豊富な科学コンピューティングライブラリがあり、JavaScriptには強力なフロントエンドフレームワークがあります。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

Dreamweaver Mac版
ビジュアル Web 開発ツール

SublimeText3 中国語版
中国語版、とても使いやすい

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。
