如何更好地避免重复代码。我尝试使用diff道具渲染albeRow两次,但我有TableCell渲染的重复代码。
{data.map((item, index) =>
selectable && !!selected
? <TableRow
hover
onClick={() => {
onSelect(selected.includes(index)
? selected.filter(x => x != index)
: [...selected, index])}}
role="checkbox"
aria-checked={selected.includes(index)}
tabIndex="-1"
key={index}
selected={selected.includes(index)}
>
<TableCell checkbox>
<Checkbox checked={selected.includes(index)}/>
</TableCell>
{columns.map(({dataKey, cellRenderer, numeric}, index) =>
<TableCell key={index} numeric={numeric}>
{(cellRenderer || defaultCellRenderer)({item, dataKey})}
</TableCell>)}
</TableRow>
: <TableRow hover key={index}>
{columns.map(({dataKey, cellRenderer, numeric}, index) =>
<TableCell key={index} numeric={numeric}>
{(cellRenderer || defaultCellRenderer)({item, dataKey})}
</TableCell>)}
</TableRow>
)}
答案 0 :(得分:1)
据我所知,selectable && !!selected
是处理选择行的选项的主要条件。在这种情况下,我会使用它,并将组件渲染为:
import React from 'react'
import { TableRow, TableCell, Checkbox } from 'anything'
export default function YourCompoment({
columns,
data,
selectable,
selected,
onSelect,
}) {
const canSelect = selectable && !!selected
return (
<div>
{data.map((item, index) =>
<TableRow
hover
onClick={canSelect && () => {
onSelect(
selected.includes(index)
? selected.filter(x => x != index)
: [...selected, index]
)
}}
role={canSelect ? 'checkbox' : 'anyOtherValue'}
aria-checked={canSelect && selected.includes(index)}
tabIndex="-1"
key={index}
selected={canSelect && selected.includes(index)}
>
{canSelect &&
<TableCell checkbox>
<Checkbox checked={selected.includes(index)} />
</TableCell>}
{columns.map(({ dataKey, cellRenderer, numeric }, columnIndex) =>
<TableCell key={columnIndex} numeric={numeric}>
{(cellRenderer || defaultCellRenderer)({ item, dataKey })}
</TableCell>
)}
</TableRow>
)}
</div>
)
}