मेरे पास निम्नलिखित के रूप में एक प्रतिक्रिया घटक App
है, इसकी एक स्थिति WHRatio
है, और मेरा div
घटक WHRatio
मान का उपयोग height
मान की गणना करने के लिए करेगा। मेरे निम्नलिखित तरीके से, यह काम कर सकता है, यह मूल घटक स्थिति WHRatio
सफलतापूर्वक प्राप्त कर सकता है।
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>
</>
);
}
जैसा कि हम जानते हैं, styled-components
घटकों को स्टाइल करने के लिए टैग किए गए टेम्प्लेट शाब्दिक का उपयोग करता है।
// something like this
const Container = styled.div`
background-color: orange;
width: 100px;
height: 200px;
`
मैं इनलाइन शैली के बजाय अपने घटक को स्टाइल करने के लिए टैग किए गए टेम्पलेट अक्षर का उपयोग करना चाहता हूं। तो मैं टैग किए गए टेम्पलेट अक्षर का उपयोग करके बाल स्टाइल घटक में मूल घटक की स्थिति कैसे प्राप्त करूं?
2 जवाब
आप ऐसा करते हैं कि प्रॉप्स वैल्यू को कस्टम स्टाइल में पास करके, उदाहरण के लिए:
const Container = styled.div`
background-color: orange;
width: 100px;
height: ${props => props.customHeight + "px"}
`
पूर्ण उदाहरण:
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>
</>
);
}
इसके अलावा, आप सीएसएस सुविधा का उपयोग कर सकते हैं और इसे स्टाइल वाले घटक में भेज सकते हैं, अधिक विवरण और उदाहरणों के लिए आप इसे देख सकते हैं url .
उदाहरण 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};
`
क्या आपने कुछ इस तरह की कोशिश की:
आप अपना आकार पास करते हैं जैसे:
<Container sizeWidth={sizeWidth}/>
तो आपके स्टाइल कंपोनेंट में ऐसा होगा:
const Container = styled.div`
width: ${(props) => props.sizeWidth + "px"};
`