父组件使子组建滚动

发布于:2024-06-28 ⋅ 阅读:(108) ⋅ 点赞:(0)

在使用 TypeScript 和 React 时,实现父组件控制子组件内部元素的滚动,可以使用 refuseImperativeHandle。以下是如何在 .tsx 文件中实现这个功能的详细步骤:

子组件(Son.tsx)

import React, { forwardRef, useImperativeHandle, useRef } from 'react';

// 定义子组件的 ref 接口
export interface SonRef {
  scrollUp: () => void;
}

const Son = forwardRef<SonRef>((_, ref) => {
  const textContainerRef = useRef<HTMLDivElement>(null);

  useImperativeHandle(ref, () => ({
    scrollUp() {
      if (textContainerRef.current) {
        textContainerRef.current.scrollTop -= 300;
      }
    },
  }));

  return (
    <div>
      <div className="textContainer" ref={textContainerRef} style={{ overflow: 'auto', maxHeight: '400px' }}>
        {/* 示例内容,可以替换为实际内容 */}
        {Array.from({ length: 100 }, (_, i) => (
          <p key={i}>This is line {i + 1}</p>
        ))}
      </div>
    </div>
  );
});

export default Son;

父组件(Father.tsx)

import React, { useRef } from 'react';
import Son, { SonRef } from './Son'; // 根据实际路径修改

const Father: React.FC = () => {
  const sonRef = useRef<SonRef>(null);

  const handleScrollUp = () => {
    if (sonRef.current) {
      sonRef.current.scrollUp();
    }
  };

  return (
    <div>
      <button onClick={handleScrollUp}>Scroll Up</button>
      <Son ref={sonRef} />
    </div>
  );
};

export default Father;

解释

  1. 子组件 (Son.tsx):

    • 使用 useRef 创建一个引用 textContainerdiv
    • 使用 useImperativeHandlescrollUp 方法暴露给父组件。
    • 定义 SonRef 接口来描述暴露的方法,以便在父组件中使用该类型。
  2. 父组件 (Father.tsx):

    • 使用 useRef 创建一个引用子组件的 ref,类型为 SonRef
    • 在点击按钮时,通过 ref 调用子组件的 scrollUp 方法,实现滚动。

通过这种方式,父组件可以在不直接操作子组件 DOM 的情况下,控制子组件内部的滚动行为。使用 TypeScript 可以确保类型安全,并提供更好的开发体验。