如何在 ReactJS 中将具有属性的 CSS 转换为 MaterialUI 样式

How to convert CSS with properties to MaterialUI Styles in ReactJS

我有以下 CSS:

[contentEditable=true]:empty:not(:focus):before{
    content:attr(data-text)
}

允许在内容可编辑 div 没有内容时显示占位符。我正在使用 Material-UI 样式,所以我需要这样的东西:

const styles = theme => ({
  div[contentEditable=true]:empty:not(:focus):before: {
    content:attr(data-text)
  }
});

我怎样才能做到这一点?有什么想法吗?

谢谢。

下面是一些语法选项,具体取决于您是想直接在 div (editableDiv) 上还是在祖先元素 (container 上指定 class ).两者之间的唯一区别是当定位后代时 & 之后的 space。

import React from "react";
import ReactDOM from "react-dom";

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  container: {
    "& [contentEditable=true]:empty:not(:focus):before": {
      content: "attr(data-text)"
    }
  },
  editableDiv: {
    "&[contentEditable=true]:empty:not(:focus):before": {
      content: "attr(data-text)"
    }
  }
});
function App() {
  const classes = useStyles();
  return (
    <div>
      <div className={classes.container}>
        <div contentEditable data-text="Click here to edit div 1" />
        <div contentEditable data-text="Click here to edit div 2" />
      </div>
      <div
        className={classes.editableDiv}
        contentEditable
        data-text="Click here to edit div 3"
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

相关文档:https://cssinjs.org/jss-plugin-nested?v=v10.0.0#use--to-reference-selector-of-the-parent-rule