在映射循环中生成多个引用



如果我以正确的方式使用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>
))}
</>
);
}

在原始示例中,当我console.log(itemsRef);时,我收到// Object {current: Array[3]}不同之处在于我在版本中使用了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。根据您的控制台,它可能会也可能不会显示数组对象的非元素属性。

您可以使用map中的index使它们成为数组元素(但请继续阅读!

{cities.condition.map((condition, index) => (
<div
key={condition.id}
ref={el => (itemsRef.current[index] = el)}
>
Weather: {condition.weather}
<br />
Activity: {condition.activity}
</div>
))}

但是根据你对这些 ref 所做的事情,我会避免这样做,而是让每个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} />
))}

即使我们使用数组元素,您当前方式的一个问题是,即使它们过去引用的 DOM 元素消失了(它们将nullitemRefs也会继续包含三个元素,因为 React 在删除元素时会用null调用您的ref回调, 而你的代码只是将该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>
))}

但同样,我倾向于制作一个管理自己的 ref 的Condition组件。

相关内容

  • 没有找到相关文章

最新更新