![](/img/trans.png)
[英]How do I pass button click event if I am using this.props.children in React
[英]How do I pass both event and props?
我寫了一個 function,當按下 Enter 鍵時,調用所需的 function。 它看起來像這樣:
const handleKeyDown = (event) => {
if (event.key === 'Enter') {
event.preventDefault ();
handleSubmit ();
}
}
在正確的地方我只是用onKeyDown = {handleKeyDown}
調用它。 但是碰巧我在很多地方都使用了這個function,不知何故我不想只是重復代碼。 (甚至handleKeyDown 函數的名稱也到處重復)
And as a result, I created a separate file and threw the function there, but it did not work, I think it was due to the fact that I passed the event and props arguments to the function, and when I called this function I did不知道要傳遞什么而不是事件(當然,我可以將事件傳遞給我稱之為 function 的地方,但那里也有道具,這也不起作用)。
那么我該怎么做呢?
如果我理解正確,您希望從單獨的文件中導入事件處理程序,而不是組件。 我猜你在問道具,因為你想從組件傳遞一個handleSubmit
。 在這種情況下,一種選擇是在附加處理程序時將回調傳遞給生成器。 您可以按如下方式執行此操作。
my_event_handler.js
// Returns an event handler with the callback held in its closure
export default function createListener(handleSubmit) {
return (event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleSubmit();
}
};
}
my_component.jsx
import createOnKeyHandler from './my_event_handler';
function MyComponent(props) {
const submitHandler = () => { console.log('woot'); };
return (
<input
placeholder='abc'
onKeyDown={createOnKeyHandler(submitHandler)}
/>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.