提问者:小点点

在映射循环中生成多个refs


我仍然不知道是否正确使用useref([]);,因为itemsref返回对象{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>
  ));
}

共1个答案

匿名用户

在将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>
))}

但是根据您对这些refs所做的工作,我会避免这样做,而是让每个条件成为它自己的组件:

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),因为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>
))}

或者是映射:

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组件来管理自己的ref。