【问题标题】:What typescript type use for function argument?什么打字稿类型用于函数参数?
【发布时间】:2021-10-27 10:40:31
【问题描述】:

onClick 被触发时,按下的HTML 元素(即<svg> 元素)作为参数传递给handleClick(该参数称为“pressedElement”)。由于我已经为其分配了any 类型并且使用any 被认为是一种不好的做法,我想用另一种Typescript 类型替换any。我应该使用什么类型而不是使用any

这是组件的代码:

import useScrollTrigger from '@material-ui/core/useScrollTrigger';
import Zoom from '@material-ui/core/Zoom';
import './Catalog.scss';
  
  const ScrollTop = (props: any) => {
    const { children, window } = props;
    const trigger = useScrollTrigger({
      target: window ? window() : undefined,
      disableHysteresis: true,
      threshold: 100,
    });
  
    const handleClick = (pressedElement: any) => {
      
      const anchor = (pressedElement.ownerDocument || document).querySelector('#back-to-top-anchor');
  
      if (anchor) {
        anchor.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    };
  
    return (
      <Zoom in={trigger}>
        <div 
          onClick={({ target }) => handleClick(target)} 
          role="presentation" 
          className="scrollTop"
        >
          {children}
        </div>
      </Zoom>
    );
  }

  export default ScrollTop;

【问题讨论】:

  • 我猜像HTMLSVGElement

标签: javascript reactjs typescript typescript-typings


【解决方案1】:

onClick事件的第一个参数是React.FocusEvent,你的解构目标是EventTarget & HTMLInputElement。

我已在此代码框上复制了您的代码,您可以看到类型正常工作,并且将鼠标悬停在它们上会显示类型 https://codesandbox.io/s/snowy-cloud-jlqwx?file=/src/Component.tsx

【讨论】:

  • React.FocusEvent 焦点事件对我不起作用,尽管您的回答让我知道如何替换 any。我通过使用eact.MouseEvent&lt;HTMLInputElement&gt; 做到了
  • 我也打算推荐一个 React.MouseEvent - 但我认为它们都有效。无论如何很高兴它起作用了
猜你喜欢
  • 2019-01-10
  • 2021-01-03
  • 1970-01-01
  • 2019-03-20
  • 2022-01-12
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 2018-05-02
相关资源
最近更新 更多