反应挂钩参考

时间:2018-12-08 00:10:32

标签: reactjs

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

<canvas ref='canvas'></canvas>

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

谢谢!

3 个答案:

答案 0 :(得分:11)

使用钩子,您可以使用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>
    </>
  );
}

在此处查看useRef文档: https://reactjs.org/docs/hooks-reference.html#useref

答案 1 :(得分:2)

仅显示一个示例,以非冗长的方式在React Native中为我工作。

export function Screen() {

   /*
    * Call function for example of access to the component, 
    * being able to access calls to its functions.
    */
    const callRef = () => {
       testeRef.example();
    };

    return (
       <CustomComponent ref={(e) => testRef = e}></CustomComponent>
    );
}

答案 2 :(得分:0)

如果您想在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>
    );
};
相关问题