【问题标题】:Change the styling of a child div with CSS hover on parent JSX在父 JSX 上使用 CSS 悬停更改子 div 的样式
【发布时间】:2019-03-09 18:54:01
【问题描述】:

我正在使用 material-ui 表。在其中我正在映射行:

.map(row => (
  <TableRow
    className={classes.clickableRow}
    key={row[rowKey]}
  >
    {generateTableCheckbox(row)}
    {
      columns.map(column => (
        <TableCell
          onClick={onRowClick && !row.disabled
            ? event => onRowClick(event, row)
            : null}
          key={column.field}
          className={classes.body}
          title={column.alt ? column.alt(row) : row[column.field]}
        >
          {column.format ? column.format(row) : row[column.field]}
        </TableCell>
      ))
    }
    {generateTableHoverOptions(row)}
  </TableRow>
))

如您所见,className 设置为 clickableRow

TableRow 包含一个悬停选项 div,该 div 使用此函数呈现并放置在右侧:

const generateTableHoverOptions = () => {
  if (selected) {
    return (
      <TableCell className={classes.rightHoverIcon}>
        <Icon>expand_more</Icon>
      </TableCell>
    );
  }
  return null;
};

当悬停在clickableRow 上时,我希望能够更改从该函数返回的&lt;TableCell /&gt;backgroundColor(类名是rightHoverIcon)。这是我一直在尝试使用的 js CSS:

clickableRow: {
  '&:hover': {
    backgroundColor: theme.palette.background.default,
    cursor: 'pointer',
  },
  '&:hover > .rightHoverIcon': {
    backgroundColor: 'red',
  },
},
rightHoverIcon: {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  marginTop: 1,
  height: 49,
  position: 'absolute',
  right: 0,
  borderBottomWidth: 1,
  borderBottomColor: 'rgba(224, 224, 224, 1)',
},

期望以 div 为目标的代码是 '&amp;:hover &gt; .rightHoverIcon',我尝试了其他变体,例如 '&amp;:hover ~ .rightHoverIcon'&amp;:hover .rightHoverIcon,但似乎都没有工作。

我检查了关于 SO 的其他问题,虽然类似,但它们与我的问题不同。如果有人有任何想法,请告诉我!

提前致谢

【问题讨论】:

  • 你为什么要用 js 做样式——为什么不直接用 css?
  • 我们正在从import { withStyles } from '@material-ui/core'; 导出带有withStyles 的组件

标签: javascript html css material-ui jsx


【解决方案1】:

&amp;:hover &gt; .rightHoverIcon 期望.rightHoverIconclickableRow直接子,但它不是(中间有一个表格单元格)。删除&gt;,这样您就可以使用descendant combinator 而不是child combinator

clickableRow: {
  '&:hover': {
    backgroundColor: theme.palette.background.default,
    cursor: 'pointer',
  },
  '&:hover .rightHoverIcon': {
  // -----^
    backgroundColor: 'red',
  },
},

或者,或者,如果你想使用子组合器,你至少需要两个(假设TableCell 只在其父元素和图标之间放置一个元素),例如&amp;:hover &gt; something-for-the-cell &gt; .rightHoverIcon.

【讨论】:

  • 你能帮我只在父元素悬停时显示图标吗?如果没有悬停在父 Child 上应该是不可见的。这个例子很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-31
  • 2013-11-07
  • 2014-11-27
  • 2019-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多