javascript - html 元素数组或字符串 typescript
问题描述
简而言之,我想拥有stings
或HTMLInputElements
作为我的类型。
const tableHeaders = [
<input type="checkbox" />,
"Some String",
"Another Some String",
];
零件
import React, { ReactChildren } from 'react';
interface TableProps {
headers: (string | HTMLInputElement)[];
}
export const Table = ({ headers }: TableProps) => (
<table>
<thead>
<tr>
{headers.map((name: string) => (
<th key={name}>{name}</th>
))}
</tr>
</thead>
</table>
);
错误
Type '(string | Element)[]' is not assignable to type 'string[]'.
Type 'string | Element' is not assignable to type 'string'.
Type 'Element' is not assignable to type 'string'. TS2322
160 | {!noResults && (
161 | <TableShell data-id="TableShell">
> 162 | <Table headers={tableHeaders}>
| ^
163 | {state.map(
164 | ({
165 | id,
期望的结果:
将任意标题作为任何 html 输入和/或字符串。
一个可能的解决方案?
import React, { ReactChildren } from 'react';
type headerType = ReactChildren | React.ReactNode | string;
interface TableProps {
headers: headerType[];
}
export const Table = ({ headers }: TableProps) => (
<table>
<thead>
<tr>
{headers.map(
(name: headerType, index) => (
<th key={`${index}_tableHeader`}>{name}</th>
)
)}
</tr>
</thead>
</table>
);
解决方案
推荐阅读
- heroku - puppeteer 部署到 heroku 时失败
- javascript - 写入 cookie 的 React 组件的奇怪行为
- css - 移动模式下不显示文字阴影
- excel - Excel/ Libreoffice Calc - 确定日期范围并仅汇总该范围内月份的值
- c# - 最短路线算法非常慢
- javascript - 我如何使用平面列表返回对象列表?
- c++ - delete c in void insert() 打印无限数,如果我将其注释掉,我会得到正确的输出
- java - 使用单个 json 但发布多个 AVRO 消息
- arrays - 如何将用户输入收集到 VBA 中的数组
- c++ - SFINAE 检测 CTAD 扣除指南的明确性