如何在typescript函数组件中传递函数作为参数

hgb9j2n6  于 2023-01-06  发布在  TypeScript
关注(0)|答案(2)|浏览(228)

我想传递一个函数和一个数字作为参数到一个typescript功能组件,我使用了any关键字,并没有任何错误,但当我运行代码,从浏览器的控制台的错误是如下.使用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>
  );
};
pbpqsu0x

pbpqsu0x1#

与其作为any传递,您可以更具体地作为() => void传递。我还建议添加一个prop type
例如,type SampleProps = { handleDrawerToggle: () => void; drawerWidth: number }
比如说

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

ttcibm8c2#

您忘记了组件 prop 的{}

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

如果不编写{},则代码handleDrawerToggle类似于props,而props是一个对象。

相关问题