1

如果我使用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>
  ));
}
4

1 回答 1

2

refs添加to时使用的是非数字字符串键itemRefs,这意味着它们最终成为数组对象的属性,但不是数组元素,因此它的长度保持不变0。根据您的控制台,它可能会或可能不会在数组对象上显示非元素属性。

您可以使用indexfrom将它们设为数组元素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,因为 React使用when调用您的ref回调null该元素被删除,您的代码只是将其存储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管理自己的 ref 的组件。

于 2020-06-26T15:03:17.883 回答