如何在 TypeScript 功能组件中将函数作为参数传递

问题描述 投票:0回答:3

我想将一个函数和一个数字作为参数传递给打字稿功能组件,我使用了

any
关键字,IDE 中没有任何错误,但是当我运行代码时,浏览器控制台中的错误是下列的。使用 javascript 代码按预期工作,请知道我如何修复此错误

react-dom.development.js:4054 Uncaught Error: Expected `onClick` listener to be a function, instead got a value of `object` type.
    at getListener (react-dom.development.js:4054:1)
    at accumulateSinglePhaseListeners (react-dom.development.js:9317:1)
    at extractEvents$4 (react-dom.development.js:8976:1)
    at extractEvents$5 (react-dom.development.js:9004:1)
    at dispatchEventsForPlugins (react-dom.development.js:9096:1)
    at react-dom.development.js:9288:1
    at batchedUpdates$1 (react-dom.development.js:26140:1)
    at batchedUpdates (react-dom.development.js:3991:1)
    at dispatchEventForPluginEventSystem (react-dom.development.js:9287:1)

Uncaught TypeError: handleDrawerToggle is not a function

// Typescript
const App = () => {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const drawerWidth = 240;
  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };
  return (
    <div>
      <Sample
        handleDrawerToggle={handleDrawerToggle}
        drawerWidth={drawerWidth}
      />
      {mobileOpen && <h1>hello</h1>}
    </div>
  );
};

const Sample = ( handleDrawerToggle:any, drawerWidth:any ) => {
  return (
    <div>
      <button onClick={handleDrawerToggle} style={{ width: `${drawerWidth}` }}>
        Testv
      </button>
    </div>
  );
};

reactjs typescript
3个回答
2
投票

您可以更具体,并将其传递为

any
,而不是传递为
() => void
。我还建议添加一个道具
type

例如,

type SampleProps = { handleDrawerToggle: () => void; drawerWidth: number }

所以类似

const Sample = ({ handleDrawerToggle, drawerWidth }: SampleProps) => {
  return (
    <div>
      <button onClick={handleDrawerToggle} style={{ width: `${drawerWidth}px` }}>
        Testv
      </button>
    </div>
  );
};

0
投票

您忘记了组件的 props 的

{}
:

const Sample = ({ handleDrawerToggle, drawerWidth }) => {
  return (
    <div>
      <button onClick={handleDrawerToggle} style={{ width: `${drawerWidth}` }}>
        Testv
      </button>
    </div>
  );
};

使用你的代码,如果不写

{}
,handleDrawerToggle 就像 props,并且 props 是一个对象。


0
投票

您需要先定义 Props 类型。

type PropsType = {
  handleDrawerToggle: () => void; // function prop
  drawerWidth: number
}

const Sample: React.FC<PropsType> = ({ handleDrawerToggle, drawerWidth }) => {.....}

© www.soinside.com 2019 - 2024. All rights reserved.