美文网首页
useImperativeHandle

useImperativeHandle

作者: 我是Msorry | 来源:发表于2021-01-11 09:52 被阅读0次

    理解上应该叫setRef,当暴露一个ref给外面时,可以用这个Hook对ref自定义

    function App() {
      const buttonRef = useRef(null);
      useEffect(() => {
        console.log(buttonRef.current);
      });
      return (
        <div className="App">
          <Button2 ref={buttonRef}>按钮</Button2>
          <button
            className="close"
            onClick={() => {
              console.log(buttonRef);
              buttonRef.current.x();
            }}
          >
            x
          </button>
        </div>
      );
    }
    
    const Button2 = React.forwardRef((props, ref) => {
      const realButton = createRef(null);
      const setRef = useImperativeHandle;
      setRef(ref, () => {
        return {
          x: () => {
            realButton.current.remove();
          },
          realButton: realButton
        };
      });
      return <button ref={realButton} {...props} />;
    });
    
    function App() {
      const buttonRef = useRef(null);
      useEffect(() => {
        console.log(buttonRef.current);
      });
      return (
        <div className="App">
          <Button2 ref={buttonRef}>按钮</Button2>
          <button
            className="close"
            onClick={() => {
              console.log(buttonRef);
              buttonRef.current.remove();
            }}
          >
            x
          </button>
        </div>
      );
    }
    
    const Button2 = React.forwardRef((props, ref) => {
      return <button ref={ref} {...props} />;
    });
    
    

    相关文章

      网友评论

          本文标题:useImperativeHandle

          本文链接:https://www.haomeiwen.com/subject/aqqarktx.html