ReactJS表格单元格循环:如何为每行项目遍历角色?
Hey there! Let's get that role rendering sorted out for your React table. Since you're new to React, I'll break this down clearly so you can follow along.
First, let's look at the issue in your current code: your Cell function is just returning a comma, and you're referencing args but the parameter is named props—plus you aren't actually looping through the roles array yet.
Fixing the Roles Column Rendering
Here's how to update your columns array's Roles entry to properly loop through and display each role:
{ id: 'roles', Header: 'Roles', accessor: 'roles', Cell: (props: { value: Array<{name: string}> }) => { // Handle empty roles case to avoid blank cells if (!props.value || props.value.length === 0) { return <span>No roles assigned</span>; } // Loop through the roles array and render each name, separated by commas return props.value.map((role, index) => ( <span key={index}> {role.name} {/* Add a comma only if it's not the last role */} {index !== props.value.length - 1 ? ', ' : ''} </span> )); }, }
What's happening here?
- We first check if
props.value(which is therolesarray for the current row) is empty or undefined. This prevents errors if a project has no roles, and shows a friendly message instead of a blank cell. - We use
Array.map()to iterate over each role in the array. For every role, we render itsnameproperty. - The
keyprop is required for React list items—usingindexworks here if your role list doesn't change order often, but if each role has a uniqueid, use that instead for better performance. - We add a comma after each role except the last one to keep the formatting clean.
Alternative (Shorter) Version
If you prefer a more concise approach, you can use Array.map() combined with join() to create a comma-separated string:
Cell: (props: { value: Array<{name: string}> }) => { if (!props.value || props.value.length === 0) { return <span>No roles assigned</span>; } return <span>{props.value.map(role => role.name).join(', ')}</span>; }
This achieves the same result, but renders all roles as a single string wrapped in a <span>.
Full Updated Columns Array
Just to make it clear, here's how your complete columns array should look:
columns={[ { Header: 'Name', accessor: 'name' }, { Header: 'Client', accessor: 'client.name' }, { Header: 'Type', accessor: 'type' }, { id: 'roles', Header: 'Roles', accessor: 'roles', Cell: (props: { value: Array<{name: string}> }) => { if (!props.value || props.value.length === 0) { return <span>No roles assigned</span>; } return props.value.map((role, index) => ( <span key={index}> {role.name} {index !== props.value.length - 1 ? ', ' : ''} </span> )); }, }, ]}
That should do it! Now each row's Roles cell will display all associated roles in a clean, comma-separated format.
内容的提问来源于stack exchange,提问作者Kiril Vodenicharov

