如果我使用useRef([]);
正确的方法作为itemsRef
返回值,我仍然会感到困惑Object {current: Array[0]}
。在这里起作用:https : //codesandbox.io/s/zealous-platform-95qim?file=/src/ App.js: 0-1157
import React, { useRef } from "react";
import "./styles.css";
export default function App() {
const items = [
{
id: "asdf2",
city: "Berlin",
condition: [
{
id: "AF8Qgpj",
weather: "Sun",
activity: "Outside"
}
]
},
{
id: "zfsfj",
city: "London",
condition: [
{
id: "zR8Qgpj",
weather: "Rain",
activity: "Inside"
}
]
}
];
const itemsRef = useRef([]);
// Object {current: Array[0]}
// Why? Isn't it supposed to be filled with my refs (condition.id)
console.log(itemsRef);
return (
<>
{items.map(cities => (
<div key={cities.id}>
<b>{cities.city}</b>
<br />
{cities.condition.map(condition => (
<div
key={condition.id}
ref={el => (itemsRef.current[condition.id] = el)}
>
Weather: {condition.weather}
<br />
Activity: {condition.activity}
</div>
))}
<br />
<br />
</div>
))}
</>
);
}
在原始示例中,// Object {current: Array[3]}
当我收到消息时,我收到console.log(itemsRef);
的区别是,我在我的版本itemsRef.current[condition.id]
中将其用作嵌套映射循环,因此i
不起作用。
import React, { useRef } from "react";
import "./styles.css";
export default function App() {
const items = ["sun", "flower", "house"];
const itemsRef = useRef([]);
// Object {current: Array[3]}
console.log(itemsRef);
return items.map((item, i) => (
<div key={i} ref={el => (itemsRef.current[i] = el)}>
{item}
</div>
));
}
在添加refs
到时itemRefs
,您使用的是非数字字符串键,这意味着它们最终将成为数组对象的属性,而不是数组元素的属性,因此其长度保持不变0
。根据您的控制台,它可能会或可能不会在数组对象上显示非元素属性。
您可以通过使用index
from来使它们成为数组元素map
(但请继续阅读!):
{cities.condition.map((condition, index) => (
<div
key={condition.id}
ref={el => (itemsRef.current[index] = el)}
>
Weather: {condition.weather}
<br />
Activity: {condition.activity}
</div>
))}
但是根据您对这些引用的处理方式,我会避免这样做,而是建议将每个引用都制作成condition
自己的组件:
const Condition = ({weather, activity}) => {
const itemRef = useRef(null);
return (
<div
ref={itemRef}
>
Weather: {weather}
<br />
Activity: {activity}
</div>
);
};
然后摆脱itemRefs
并做:
{cities.condition.map(({id, weather, activity}) => (
<Condition key={id} weather={weather} activity={activity} />
))}
即使我们使用数组元素,当前方式的一个问题是,itemRefs
即使它们曾经引用的DOM元素消失了(它们也会拥有null
),它仍将继续包含三个元素,因为Reactref
使用null
when调用回调元素被删除,您的代码只是将其存储null
在数组中。
或者,您可以使用一个对象:
const itemRefs = useRef({});
// ...
{cities.condition.map(condition => (
<div
key={condition.id}
ref={el => {
if (el) {
itemsRef.current[condition.id] = el;
} else {
delete itemsRef.current[condition.id];
}
}}
>
Weather: {condition.weather}
<br />
Activity: {condition.activity}
</div>
))}
或者也许是Map
:
const itemRefs = useRef(new Map());
// ...
{cities.condition.map(condition => (
<div
key={condition.id}
ref={el => {
if (el) {
itemsRef.current.set(condition.id, el);
} else {
itemsRef.current.delete(condition.id);
}
}}
>
Weather: {condition.weather}
<br />
Activity: {condition.activity}
</div>
))}
但是,我还是倾向于制作一个Condition
管理自己的引用的组件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句