尝试在反应中比较两个单元格的值,然后根据值更改样式

问题描述

我刚开始反应。

我使用 react-table 模块制作了一个表格,我试图突出显示第一列中的单元格不等于第二列中相邻单元格的所有单元格。

这是我的表格组件:

const Table = () => {

    const columns = useMemo(() => Columns,[])
    const data = useMemo(() => mock,[])
    
    

    const {
        getTableProps,getTableBodyProps,headerGroups,rows,prepareRow,state,setGlobalFilter,} = useTable({
        columns,data,},useGlobalFilter)

    const { globalFilter } = state

    return (
        < >
         
            <SearchBar searchValue={globalFilter} setSearchValue={setGlobalFilter}/>
            
           
        <div>
            
            <table {...getTableProps()}>
                <thead>

                    
                    {headerGroups.map((headerGroup) =>(
                        <tr {...headerGroup.getHeaderGroupProps()}>
                            {headerGroup.headers.map((column) => (
                                <th {...column.getHeaderProps()}>
                                    {column.render('Header')}
                                </th>
                            ))}
                        </tr>
                    ))}
                        
                </thead>
                <tbody {...getTableBodyProps()}>
                    {
                        rows.map((row) =>{
                            prepareRow(row)
                            return (
                                <tr {...row.getRowProps()}>
                                    {row.cells.map((cell,index)=> {
                                        return <td {...cell.getCellProps()} style = {{
                                            backgroundColor:{rows[0].cells[index].value!==rows[1].cells[index].value ? 'red': null}
                                        }}>{cell.render('Cell')}</td>
                                    })} 
                                </tr>
                            )
                        })
                    }
                    
                </tbody>
            </table>
        </div>
        </>
    )


        

    
}


export default Table

运行时出现两个错误

预期的“,”在

backgroundColor:{rows[0].cells[index].value!==rows[1].cells[index].value ? '红色':空}

预期的“:”在

backgroundColor:{rows[0].cells[index].value!==rows[1].cells[index].value ? '红色':空}

任何帮助将不胜感激

解决方法

{backgroundColor:(rows[0].cells[index].value!==rows[1].cells[index].value ? 'red': null)}

使用括号而不是大括号。