Tengo una App de componente de reacción como la siguiente, tiene un estado WHRatio y mi componente div usará el valor WHRatio para calcular el valor de height . De la siguiente manera, puede funcionar, puede obtener el estado del componente principal WHRatio con éxito.
import React, { useState } from "react"; export default function App() { const sizeWidth = 100; const [WHRatio, setWHRatio] = useState(1); const getContainerHeight = () => Math.floor(sizeWidth / WHRatio); const incWHRatio = () => setWHRatio(WHRatio + 1); return ( <> <div style={{ width: sizeWidth, height: getContainerHeight(), backgroundColor: "orange" }} > </div> <button onClick={incWHRatio}>Inc WHRatio</button> </> ); } Como sabemos, styled-components utilizan literales de plantilla etiquetados para diseñar los componentes.
// something like this const Container = styled.div` background-color: orange; width: 100px; height: 200px; `Quiero usar los literales de plantilla etiquetados para diseñar mi componente en lugar del estilo en línea. Entonces, ¿cómo obtengo el estado del componente principal en un componente con estilo secundario usando literales de plantilla etiquetados?
Lo haces pasando el valor de accesorios al estilo personalizado, por ejemplo:
const Container = styled.div` background-color: orange; width: 100px; height: ${props => props.customHeight + "px"} `Ejemplo completo:
import React, { useState } from "react"; import styled from "styled-components"; const Container = styled.div` background-color: orange; width: 100px; height: ${props => props.customHeight + "px"} ` export default function App() { const sizeWidth = 100; const [WHRatio, setWHRatio] = useState(1); const getContainerHeight = () => Math.floor(sizeWidth / WHRatio); const incWHRatio = () => setWHRatio(WHRatio + 1); return ( <> <Container customHeight={getContainerHeight()} ></Container> <button onClick={incWHRatio}>Inc WHRatio</button> </> ); }Además, puede usar la función css y pasarla al componente con estilo, para obtener más detalles y ejemplos, puede consultar esta url .
Ejemplo 2:
import styled, { css, keyframes } from 'styled-components' const animation = keyframes` 0% { opacity: 0; } 100 { opacity: 1; } ` const animationRule = css` ${animation} 1s infinite alternate; ` const Component = styled.div` animation: ${animationRule}; `Probaste algunos como este:
pasas tu sizeWidth como
<Container sizeWidth={sizeWidth}/>entonces en su componente con estilo será como:
const Container = styled.div` width: ${(props) => props.sizeWidth + "px"}; `