ReactJS + Material-UI:如何在Material-UI <Table/>的<TableRow/>之间交替使用颜色?

21

我目前有一个Material-UI的<Table/> (http://www.material-ui.com/#/components/table),希望每一行在蓝色和紫色之间切换。所以第一行将是蓝色,下一行将是紫色,以此类推对于添加的任何其他行都是如此。

如何动态地在所有新增加的行之间切换两种颜色?

render(){

    return(
        <Table
          multiSelectable={true}
        >
          <TableHeader>
            <TableRow>
              <TableHeaderColumn>First Name</TableHeaderColumn>
              <TableHeaderColumn>Last Name</TableHeaderColumn>
              <TableHeaderColumn>Color</TableHeaderColumn>
            </TableRow>
          </TableHeader>
          <TableBody
            displayRowCheckbox={true}
            stripedRows
          >
              <TableRow>
                <TableRowColumn>John</TableRowColumn>
                <TableRowColumn>Smith</TableRowColumn>
                <TableRowColumn>Red</TableRowColumn>
              </TableRow>
              <TableRow>
                <TableRowColumn>Paul</TableRowColumn>
                <TableRowColumn>Row</TableRowColumn>
                <TableRowColumn>Black</TableRowColumn>
              </TableRow>
              <TableRow>
                <TableRowColumn>Doe</TableRowColumn>
                <TableRowColumn>Boe</TableRowColumn>
                <TableRowColumn>Pink</TableRowColumn>
              </TableRow>
              <TableRow>
                <TableRowColumn>Frank</TableRowColumn>
                <TableRowColumn>Done</TableRowColumn>
                <TableRowColumn>White</TableRowColumn>
              </TableRow>
              <TableRow>
                <TableRowColumn>Lucy</TableRowColumn>
                <TableRowColumn>Ju</TableRowColumn>
                <TableRowColumn>Orange</TableRowColumn>
              </TableRow>
          </TableBody>
        </Table>

提前致谢


https://github.com/callemall/material-ui#customization - el solo lobo
5个回答

17

您可以创建一个带样式的TableRow,并应用奇偶CSS规则


Material UI 版本 5 (Styled Components)

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  '&:nth-of-type(odd)': {
    backgroundColor: "white",
  },
  '&:nth-of-type(even)': {
    backgroundColor: "grey",
  },
}));

或者
const StyledTableRow = styled(TableRow)`
  &:nth-of-type(odd) {
    background-color: ${({ theme }) => theme.palette.action.hover}; // accessing the theme
  }
  &:nth-of-type(even) {
    background-color: "grey";
  }
`;
(在Typescript和Javascript中都适用)

Material UI版本4(JSS)

使用Typescript:

const StyledTableRow = withStyles((theme: Theme) =>
  createStyles({
    root: {
      '&:nth-of-type(odd)': {
        backgroundColor: "white",
      },
      '&:nth-of-type(even)': {
        backgroundColor: "grey",
      },
    },
  }),
)(TableRow);

使用Javascript:

const StyledTableRow = withStyles((theme) => ({
  root: {
    '&:nth-of-type(odd)': {
      backgroundColor: "white",
    },
    '&:nth-of-type(even)': {
      backgroundColor: "grey",
    },
  },
}))(TableRow);

使用您的示例,以下是正确的写法:


render(){
  return(
    <Table multiSelectable={true} >
      <TableHeader>
        <TableRow>
          ...
        </TableRow>
      </TableHeader>
      <TableBody displayRowCheckbox={true} >
        <StyledTableRow>
          ...
        </StyledTableRow>
...
(stripedRows在Material-UI的新版本中已不再可用,请参见其他解决方法)

这是Material-UI在其文档中实现奇偶行样式的方式。

您可以在以下示例中看到它的效果:


2
这是正确的答案。给这个人一万美元。 - yBrodsky
还有Styled Components的解决方案吗?我设置了赏金。 - mattsmith5
当然,@mattsmith5,Material Ui已更新其文档以适用于styled,请给我几分钟,我会提供一个解决方案。 - Ricardo Dias Morais
@mattsmith5 完成了!希望能对你有所帮助。 - Ricardo Dias Morais

13

试一下。这在@version 4.4.2中运行良好。

{
this.state.data.map((row,index)=> (
 <TableRow style ={ index % 2? { background : "#fdffe0" }:{ background : "white" }}> 
...
</TableRow>
))}

希望这能帮到你。愉快编程...!


6

我有点晚了,但由于某些原因,stripedRows 对我来说不起作用,这就是我采用这种方式的原因:

只需使用模运算符在两种颜色之间切换即可。

{this.state.data.map((row)=> (
 <TableRow style ={ row.rank % 2? { background : "#fdffe0" }:{ background : "white" }}> 
...
</TableRow>
))}

@版本 4.2.1


4
你可以使用stripedRows属性使<TableBody>组件中的行在视觉上分离,但我不确定您是否可以为此选项自定义颜色。
<TableBody stripedRows > </TableBody>

或者您可以通过为<TableBody>组件设置className,并使用css奇偶规则来实现。可能还需要为这些规则设置!important以覆盖内联样式。

我没有找到解决这个问题的方法。你可以尝试自定义主题,但我认为这不是解决方案,因为颜色会在所有地方改变。我还在Github上开了一个问题,与维护者讨论这种情况。你无法追踪它,因为我可能是错误的,而且可能有解决方案。https://github.com/callemall/material-ui/issues/5286 - Alexandr Lazarev
非常感谢!我会留意的。最后一个问题,当选择复选框时,有没有办法去掉行高亮? - user3259472
我不确定我是否正确理解了您的意思。您是指取消所有行的条纹属性还是只取消其中一行的条纹属性? - Alexandr Lazarev
你在说哪个复选框呢?:) 我在你提供的代码示例中没有看到任何复选框。 - Alexandr Lazarev
4
在2016年至2019年间,“stripedRows”已经不再可用。相反,您可以进行类似的操作:{rows.map((row, index) => ( <TableRow key={row.percent} className={index%2 ? classes.lightRow : classes.darkRow}> ))} - edwardrbaker
显示剩余6条评论

2
寻找使用React Styled Components的替代方案,与此类似。
如果您正在使用Material UI,则最好选择@emotion而不是styled-component。它们非常相似,但在Material UI文档中,如果我们想要使用styled-components,有一些注意事项。因此,我更喜欢在Material UI中使用@emotion,以避免将来出现一些问题。
❗ 警告:目前在SSR项目中使用styled-components作为引擎时无法正常工作。原因是babel-plugin-styled-components未能正确地捕获@mui包中styled()实用程序的用法。有关更多详细信息,请参见此问题。我们强烈建议在SSR项目中使用emotion。Material UI 第二个原因:Material UI默认使用@emotion作为样式引擎。
对于解决方案,我将使用Material UI v5.9.2,并且此问题中许多以前的组件已经失效。我们需要替换旧组件,然后使用@emotion来向TableRow组件添加一个额外的伪类。此外,我们将覆盖TableRow内的td颜色属性,以保持所有内容在一个组件中。
import Table from "@mui/material/Table";
import TableHead from "@mui/material/TableHead";
import TableBody from "@mui/material/TableBody";
import TableRow from "@mui/material/TableRow";
import TableCell from "@mui/material/TableCell";

import styled from "@emotion/styled";

const TableRowStyled = styled(TableRow)`
  &:nth-of-type(odd) {
    background-color: blue;
  }
  &:nth-of-type(even) {
    background-color: purple;
  }
  & > td {
    color: white;
  }
`;

export default function App() {
  return (
    <div className="App">
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>First Name</TableCell>
            <TableCell>Last Name</TableCell>
            <TableCell>Color</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          <TableRowStyled>
            <TableCell>John</TableCell>
            <TableCell>Smith</TableCell>
            <TableCell>Red</TableCell>
          </TableRowStyled>
          <TableRowStyled>
            <TableCell>Paul</TableCell>
            <TableCell>Row</TableCell>
            <TableCell>Black</TableCell>
          </TableRowStyled>
          <TableRowStyled>
            <TableCell>Doe</TableCell>
            <TableCell>Boe</TableCell>
            <TableCell>Pink</TableCell>
          </TableRowStyled>
        </TableBody>
      </Table>
    </div>
  );
}

Edit dazziling-code


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接