gpt4 book ai didi

javascript - 避免重复的代码并提取此功能

转载 作者:行者123 更新时间:2023-12-03 03:32:23 24 4
gpt4 key购买 nike

如何更好地避免此处出现重复代码。我尝试使用 diff Prop 渲染 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>
)}

最佳答案

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

关于javascript - 避免重复的代码并提取此功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46033213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com