Background

所以我想用一种文本高亮 colored颜色 来设置我的组件及其所有子组件的样式,例如黄色.但我只能在组件返回包装在元素本身中的文本,并且不会处理包装在其子元素或子组件中的任何文本的情况下才能这样做.

例如,这将更改高光 colored颜色 :

import React from "react";
import { Container, styled } from "@mui/material";

const StyledContainer = styled(Container)(({ theme }) => ({
  "::selection": {
    backgroundColor: "#ffe20b"
  },

}));

function App() {
  return <StyledContainer>hello world</StyledContainer>;
}

export default App;


但是如果我将文本包装在子元素div中,样式就不起作用了.

import React from "react";
import { Container, styled } from "@mui/material";

const StyledContainer = styled(Container)(({ theme }) => ({
  "::selection": {
    backgroundColor: "#ffe20b"
  },

}));

function App() {
  return <StyledContainer><div>hello world</div></StyledContainer>;
}

export default App;



Question

How would I be able to recursively set the style throughout my App?假设我最外层的元素是<Box></Box>,它有一个名为MuiBox-root的类,我们可以使用它.

我try 过以下方法,但都不管用:


// didn't work
const StyledContainer = styled(Container)(({ theme }) => ({
  margin: theme.spacing(0),
  ".MuiBox-root::selection": {
    backgroundColor: "#ffe20b"
  },

// the following didn't work either

const StyledContainer = styled(Container)(({ theme }) => ({
  margin: theme.spacing(0),
  ".MuiBox-root > * ::selection": {
    backgroundColor: "#ffe20b"
  },

如果突出显示显示的两行文本,可以看到第一行已设置样式,而第二行未设置样式

推荐答案

您可以try 以下操作,它将适用于所有子元素

const StyledBox = styled(Box)(({ theme }) => ({
  "::selection, *::selection": {
    backgroundColor: "#ffe20b"
  }
}));

Javascript相关问答推荐

有条件的悲剧

微软Edge Select 间隙鼠标退出问题

过滤对象数组并动态将属性放入新数组

Plotly热图:在矩形上zoom 后将zoom 区域居中

嵌套异步JavaScript(微任务和macrotask队列)

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

Angular 中的类型错误上不存在获取属性

如何在ASP.NET中使用Google Charts API JavaScript将条形图标签显示为绝对值而不是负值

如何在coCos2d-x中更正此错误

未定义引用错误:未定义&Quot;而不是&Quot;ReferenceError:在初始化&Quot;之前无法访问';a';

在Reaction中的handleSubmit按钮内,useSelector值仍然为空

一个实体一刀VS每个实体多刀S

如何在Java脚本中对列表中的特定元素进行排序?

使每个<;li>;元素的 colored颜色 与随机生成的 colored颜色 列表不同(不重复

ngOnChanges仅在第二次调用时才触发

如何通过Axios在GraphQL查询中发送数组

是否可以在不更改组件标识的情况下换出Reaction组件定义(以维护状态/引用等)?如果是这样的话,是如何做到的呢?

与在编剧中具有动态价值的定位器交互

使用createBrowserRoutVS BrowserRouter的Reaction路由

如何在Reaction中设置缺省值, Select 下拉列表,动态追加剩余值?