我想传递一个函数和一个数字作为参数到一个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>
);
};
2条答案
按热度按时间pbpqsu0x1#
与其作为
any
传递,您可以更具体地作为() => void
传递。我还建议添加一个proptype
。例如,
type SampleProps = { handleDrawerToggle: () => void; drawerWidth: number }
比如说
ttcibm8c2#
您忘记了组件 prop 的
{}
:如果不编写
{}
,则代码handleDrawerToggle类似于props,而props是一个对象。