ref: React.Ref<HTMLDivElement> for React.forwardRef (ok)

https://app.gitbook.com/@learnreac/s/project/~/drafts/-MHR-5aTjAJ5Jcoyq70f/using-react-refs-in-typescript-ok

Ví dụ 1:

import * as React from "react";
const Forward = React.forwardRef((props, ref: React.Ref<HTMLDivElement>) => (
  <div ref={ref} style={{ width: "100%", height: "30px", backgroundColor: "green" }} />
));
function ForwardRef() {
    const divRef = React.useRef<HTMLDivElement>(null);
    React.useEffect(() => {
        if (divRef.current) {
            console.log(`forwardRefRef div width: ${divRef.current.clientWidth}`);
        }
    });
    return <Forward ref={divRef} />;
}
export default ForwardRef;

Ví dụ 2:

// Lấy ref thông qua props
class WrappedComponent extends Component {
  render() {
    return (
      <input 
        type="text"
        name={this.props.name}
        ref={this.props.innerRef}
       />
    )
  }
}
// Gói componentnt được bọc của chúng tôi với ForwardRef, truyền vào props giá trị của refs
const MyInput = React.forwardRef((props, ref) => {
  return (<WrappedComponent innerRef={ref} {...props} />);
});
export default MyInput;

Last updated

Was this helpful?