मैं प्रतिक्रिया में एक रेफरी का उपयोग करने की कोशिश कर रहा हूं, जो एक सरणी है जिसमें डीओएम में कई अन्य divs के संदर्भ शामिल हैं।
उपयोग के प्रभाव में, मैं divs को प्रस्तुत करने के लिए किसी ऑब्जेक्ट के माध्यम से मैप करता हूं, और मैं प्रत्येक div को एक रेफरी असाइन करता हूं। रेफरी निर्दिष्ट करने से पहले, मैं इसके लिए createRef
के साथ एक स्लॉट को इंस्टेंट करता हूं।
मैं अनिवार्य रूप से दोहराने की कोशिश कर रहा हूं कि इस उत्तर ने क्या करने का सुझाव दिया है।
जिस समस्या का मैं सामना कर रहा हूं वह यह है कि मेरा कंपाइलर undefined
देखता रहता है। मुझे यकीन नहीं है कि ऐसा क्यों हो रहा है, लेकिन यहां वह कोड है जो मेरे पास है:
import React from "react";
const items = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]
];
export default function Component() {
const [renderedItems, setRenderedItems] = React.useState();
const [height, setHeight] = React.useState(0);
const refsArray = React.useRef([]);
React.useEffect(() => {
const heightOfFirstDiv = refsArray.current[0].offsetHeight;
console.log("heightOfFirstDiv", heightOfFirstDiv); // <-- this is always undefined
setHeight(heightOfFirstDiv);
}, [renderedItems]);
React.useEffect(() => {
setRenderedItems(
items.map((item, index) => {
refsArray.current[index] = React.createRef();
return (
<div
ref={refsArray.current[index]}
style={{ height: 100, width: 40 }}
>
{item}
</div>
);
})
);
}, []);
return (
<div>
The height is: {height || "undefined"}
{renderedItems}
</div>
);
}
मुझसे यहां क्या गलत हो रहा है?
2 जवाब
आपके द्वारा लिंक किए गए प्रश्न का दूसरा उत्तर वास्तव में बेहतर और सरल है। इसे कॉलबैक रेफरी के माध्यम से कार्यान्वित किया जा सकता है:
import React from "react";
const items = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]
];
export default function Component() {
const [height, setHeight] = React.useState(0);
const refsArray = React.useRef([]);
React.useEffect(() => {
const heightOfFirstDiv = refsArray.current[0].offsetHeight;
console.log("heightOfFirstDiv", heightOfFirstDiv);
setHeight(heightOfFirstDiv);
}, [renderedItems]);
const renderedItems = items.map((item, index) => (
<div
ref={(el) => (refsArray.current[index] = el)}
key={index}
style={{ height: 100, width: 40 }}
>
{item}
</div>
));
return (
<div>
The height is: {height || "undefined"}
{renderedItems}
</div>
);
}
घटक स्थिति में प्रदान किए गए तत्वों को संग्रहीत करना एक अच्छा अभ्यास नहीं है, क्योंकि यह घटकों को जटिल, भ्रमित करने वाला और डीबग करने में कठिन बनाता है।
ऐसा इसलिए है क्योंकि आपका करंट [0] वास्तव में एक .current कुंजी के साथ एक वस्तु है, आप उस कुंजी को दिखाने के लिए अपनी ऊंचाईऑफफर्स्टडिव को संपादित करके मनचाहा मान प्राप्त कर सकते हैं।
const heightOfFirstDiv = refsArray.current[0].current.offsetHeight;
यदि आप ध्यान दें, उदाहरण पर आपने दोहराने की कोशिश की तो आप देखेंगे कि उन्होंने इस .current कुंजी को नष्ट कर दिया है, यही वह जगह है जहां से गलती हुई थी