美文网首页
useImperativeHandle

useImperativeHandle

作者: _____西班木有蛀牙 | 来源:发表于2021-08-18 15:24 被阅读0次
import React, {
  forwardRef,
  useRef,
  useImperativeHandle,
  useState
} 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 = () => {
//   const [inputRef, setInputRef] = useState<unknown>(null);
//   const handerClick = () => {
//     const { onFocus, onChangeValue } = inputRef;
//     onFocus();
//     onChangeValue("let us learn React!");
//   };
//   return (
//     <div style={{ marginTop: "50px" }}>
//       <ForwarSon ref={(node) => setInputRef(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;

相关文章

网友评论

      本文标题:useImperativeHandle

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