如何更好地避免此处的重复代码。我尝试使用diff props渲染albeRow两次,但是我有TableCell Rendering的重复代码。

{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>
)}

最佳答案

据我了解,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>
  )
}

07-26 09:43