据我所知,我可以像这样为单个元素使用refs:

const { useRef, useState, useEffect } = React; const App = () => { const elRef = useRef(); const [elWidth, setElWidth] = useState(); useEffect(() => { setElWidth(elRef.current.offsetWidth); }, []); return ( <div> <div ref={elRef} style={{ width: "100px" }}> Width is: {elWidth} </div> </div> ); }; ReactDOM.render( <App />, document.getElementById("root") ); <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <div id="root"></div>

我如何实现这个元素数组?显然不是这样的:(我知道,即使我没有尝试:)

const { useRef, useState, useEffect } = React; const App = () => { const elRef = useRef(); const [elWidth, setElWidth] = useState(); useEffect(() => { setElWidth(elRef.current.offsetWidth); }, []); return ( <div> {[1, 2, 3].map(el => ( <div ref={elRef} style={{ width: `${el * 100}px` }}> Width is: {elWidth} </div> ))} </div> ); }; ReactDOM.render( <App />, document.getElementById("root") ); <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <div id="root"></div>

我见过这个,所以才会这样。但是,我仍然不知道如何在这个简单的案例中实现这个建议。


当前回答

我们不能使用state,因为我们需要在render方法被调用之前ref是可用的。 我们不能任意多次调用useRef,但可以只调用一次:

假设arr是一个道具数组:

const refs = useRef([]);
// free any refs that we're not using anymore
refs.current = refs.current.slice(0, arr.length);
// initialize any new refs
for (let step = refs.current.length; step < arr.length; step++) {
    refs.current[step] = createRef();
}

其他回答

您可以使用父元素来获得一堆子元素。

在我的情况下,我试图得到一串输入在我的表单元素,然后我得到的形式元素,并使用它来处理所有的输入。

就像这样:

function Foo() {
    const fields = useRef<HTMLFormElement>(null);

    function handlePopUp(e) {
      e.preventDefault();
    
      Array.from(fields.current)
        .forEach((input: HTMLInputElement | HTMLTextAreaElement) => {
          input.value = '';
        });
    }

    return (
    <form onSubmit={(e) => handlePopUp(e)} ref={fields}>

      <input
        placeholder="Nome"
        required
        id="name"
        type="text"
        name="name"
      />
      <input
        placeholder="E-mail"
        required
        id="email"
        type="email"
        name="email"
      />
      <input
        placeholder="Assunto"
        required
        id="subject"
        type="text"
        name="subject"
      />
      <textarea
        cols={120}
        placeholder="Descrição"
        required
        id="description"
        name="description"
      />

      <button type="submit" disabled={state.submitting}>enviar</button>
    </form>  
    );
}

最简单和最有效的方法是根本不使用useRef。只需使用一个回调ref,在每次渲染时创建一个新的ref数组。

function useArrayRef() {
  const refs = []
  return [refs, el => el && refs.push(el)]
}

Demo

<div id="root"></div> <script type="text/babel" defer> const { useEffect, useState } = React function useArrayRef() { const refs = [] return [refs, el => el && refs.push(el)] } const App = () => { const [elements, ref] = useArrayRef() const [third, setThird] = useState(false) useEffect(() => { console.log(elements) }, [third]) return ( <div> <div ref={ref}> <button ref={ref} onClick={() => setThird(!third)}>toggle third div</button> </div> <div ref={ref}>another div</div> { third && <div ref={ref}>third div</div>} </div> ); } ReactDOM.render(<App />, document.getElementById("root")); </script> <script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script> <script src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

ref最初只是一个{current: null}对象。useRef在组件渲染之间保持对该对象的引用。当前值主要用于组件引用,但可以保存任何内容。

在某些时候应该有一个refs数组。如果数组的长度可能在不同的渲染之间变化,数组应该相应地缩放:

const arrLength = arr.length;
const [elRefs, setElRefs] = React.useState([]);

React.useEffect(() => {
  // add or remove refs
  setElRefs((elRefs) =>
    Array(arrLength)
      .fill()
      .map((_, i) => elRefs[i] || createRef()),
  );
}, [arrLength]);

return (
  <div>
    {arr.map((el, i) => (
      <div ref={elRefs[i]} style={...}>
        ...
      </div>
    ))}
  </div>
);

这段代码可以通过展开useEffect并将useState替换为useRef来优化,但应该注意的是,在呈现函数中执行副作用通常被认为是一种糟糕的做法:

const arrLength = arr.length;
const elRefs = React.useRef([]);

if (elRefs.current.length !== arrLength) {
  // add or remove refs
  elRefs.current = Array(arrLength)
    .fill()
    .map((_, i) => elRefs.current[i] || createRef());
}

return (
  <div>
    {arr.map((el, i) => (
      <div ref={elRefs.current[i]} style={...}>
        ...
      </div>
    ))}
  </div>
);

更新

新React文档显示了一个使用地图的推荐方法。

点击这里查看测试版(2022年12月)


有两种方法

对多个当前元素使用一个引用

const inputRef = useRef([]);

inputRef.current[idx].focus();

<input
  ref={el => inputRef.current[idx] = el}
/>

const {useRef} = React; const App = () => { const list = [...Array(8).keys()]; const inputRef = useRef([]); const handler = idx => e => { const next = inputRef.current[idx + 1]; if (next) { next.focus() } }; return ( <div className="App"> <div className="input_boxes"> {list.map(x => ( <div> <input key={x} ref={el => inputRef.current[x] = el} onChange={handler(x)} type="number" className="otp_box" /> </div> ))} </div> </div> ); } ReactDOM.render(<App />, document.getElementById("root")); <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

使用ref的数组 正如上面的帖子所说,不建议这样做,因为官方指南(以及内部棉绒检查)不允许它通过。 不要在循环、条件或嵌套函数中调用hook。相反,总是在React函数的顶层使用Hooks。通过遵循此规则,您可以确保在每次组件呈现时以相同的顺序调用hook。 然而,由于这不是我们目前的情况,下面的演示仍然可以工作,只是不推荐。

const inputRef = list.map(x => useRef(null));

inputRef[idx].current.focus();

<input
  ref={inputRef[idx]}
/>

const {useRef} = React; const App = () => { const list = [...Array(8).keys()]; const inputRef = list.map(x => useRef(null)); const handler = idx => () => { const next = inputRef[idx + 1]; if (next) { next.current.focus(); } }; return ( <div className="App"> <div className="input_boxes"> {list.map(x => ( <div> <input key={x} ref={inputRef[x]} onChange={handler(x)} type="number" className="otp_box" /> </div> ))} </div> </div> ); } ReactDOM.render(<App />, document.getElementById("root")); <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

假设您的数组包含非原语,您可以使用WeakMap作为Ref的值。

function MyComp(props) {
    const itemsRef = React.useRef(new WeakMap())

    // access an item's ref using itemsRef.get(someItem)

    render (
        <ul>
            {props.items.map(item => (
                <li ref={el => itemsRef.current.set(item, el)}>
                    {item.label}
                </li>
            )}
        </ul>
    )
}