美文网首页
在React中使用 useImperativeHandle 和

在React中使用 useImperativeHandle 和

作者: _____西班木有蛀牙 | 来源:发表于2021-08-26 16:42 被阅读0次
import React, {
  useRef,
  useImperativeHandle,
  useState,
  forwardRef
} from "react";

function Son(props, ref) {
  console.log(props);
  const inputRef = useRef(null);
  const [inputValue, setInputValue] = useState("");
  useImperativeHandle(
    ref,
    () => {
      const handleRefs = {
        /* 声明方法用于聚焦input框 */
        onFocus() {
          inputRef.current.focus();
        },
        /* 声明方法用于改变input的值 */
        onChangeValue(value) {
          setInputValue(value);
        }
      };
      return handleRefs;
    },
    []
  );
  return (
    <div>
      <input placeholder="请输入内容" ref={inputRef} value={inputValue} />
    </div>
  );
}

const ForwarSon = forwardRef(Son);

const Index = () => {
  let inputRef = null;

  const handerClick = () => {
    const { onFocus, onChangeValue } = inputRef;
    onFocus();
    onChangeValue("let us learn React!");
  };

  return (
    <div style={{ marginTop: "50px" }}>
      <ForwarSon
        ref={(node) => {
          inputRef = node;
        }}
      />
      <button onClick={handerClick}>操控子组件</button>
    </div>
  );
};

// class Index extends React.Component {
//   inputRef = null;

//   handerClick() {
//     const { onFocus, onChangeValue } = this.inputRef;
//     onFocus();
//     onChangeValue("let us learn React!");
//   }

//   render() {
//     return (
//       <div style={{ marginTop: "50px" }}>
//         <ForwarSon ref={(node) => (this.inputRef = node)} />
//         <button onClick={this.handerClick.bind(this)}>操控子组件</button>
//       </div>
//     );
//   }
// }

export default Index;

相关文章

网友评论

      本文标题:在React中使用 useImperativeHandle 和

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