反应挂钩参考

Kev*_*vin 15 reactjs

所以我决定将我的React Class组件重写为React Hook Component,然后在我的Class Component中

<canvas ref='canvas'></canvas>
Run Code Online (Sandbox Code Playgroud)

这种方法不再有效。那我该如何使用裁判呢?在文档中只说refs仍然有效。

谢谢!

Car*_*ior 30

使用挂钩,您可以使用useRef挂钩。

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

useRef这里查看文档:https : //reactjs.org/docs/hooks-reference.html#useref


Ily*_*nov 6

如果您想在map函数中使用refs:

export default () => {
    const items = ['apple', 'orange', 'mango'];

    // 1) create an array of refs
    const itemRefs = useRef(items.map(() => React.createRef()));

    useEffect(() => {
        // 3) access a ref, for example 0
        itemRefs.current[0].current.focus()
    }, []);

    return (
        <ul>
            {items.map((item, i) => (
                // 2) attach ref to each item
                <li key={item} ref={itemRefs.current[i]}>{item}</li>
            ))}
        </ul>
    );
};
Run Code Online (Sandbox Code Playgroud)