在React中使用 useImperativeHandle 和 forwardRef 操作子组件

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 (
    
); } const ForwarSon = forwardRef(Son); const Index = () => { let inputRef = null; const handerClick = () => { const { onFocus, onChangeValue } = inputRef; onFocus(); onChangeValue("let us learn React!"); }; return (
{ inputRef = node; }} />
); }; // class Index extends React.Component { // inputRef = null; // handerClick() { // const { onFocus, onChangeValue } = this.inputRef; // onFocus(); // onChangeValue("let us learn React!"); // } // render() { // return ( //
// (this.inputRef = node)} /> // //
// ); // } // } export default Index;

你可能感兴趣的:(在React中使用 useImperativeHandle 和 forwardRef 操作子组件)