Fondo
Así que quiero diseñar mi componente y todos sus elementos secundarios con un color de resaltado de texto para que sea amarillo, por ejemplo. Pero solo puedo hacerlo si el componente devuelve el texto envuelto dentro del propio elemento, y no funcionará con ningún texto envuelto en sus elementos secundarios o componentes secundarios.
Por ejemplo, esto cambiará el color de resaltado:
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; Pero si envuelvo el texto en un div de elemento secundario, el estilo no funcionará.
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;Pregunta
¿Cómo podría establecer recursivamente el estilo en mi aplicación? Digamos que mi elemento más externo es un <Box></Box> y tiene una clase llamada MuiBox-root que podemos usar.
He intentado lo siguiente pero ninguno funcionó:
// 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" },Si resalta las dos líneas de texto mostradas, puede ver que la primera línea tiene estilo mientras que la segunda no. Aquí está elenlace de codesandbox
Puede intentar seguirlo, funcionará para todos los elementos secundarios.
const StyledBox = styled(Box)(({ theme }) => ({ "::selection, *::selection": { backgroundColor: "#ffe20b" } }));