记录React onClick 点击事件传参的 4 种方式
方式一:使用内联箭头函数
import React, { MouseEvent } from "react";function App() {const handleClick = (event: MouseEvent<HTMLButtonElement>, name: string) => {console.log(event)console.log(name)}return (<div><button onClick={(event) => handleClick(event, 'wj')}>点我</button></div>);
}export default App;
方式二:使用函数返回一个函数
import React, { MouseEvent } from "react";function App() {const handleClick = (params: { name: string }) => (event: MouseEvent<HTMLButtonElement>) => {console.log(event)console.log(params)}return (<div><button onClick={handleClick({ name: 'wj' })}>点我</button></div>);
}export default App;
方式三:使用useCallback hook
import React, { MouseEvent, useCallback } from "react";function App() {const handleClick = useCallback((name: string, age: number) => {return (event: MouseEvent<HTMLButtonElement>) => {console.log(name)console.log(age)console.log(event)}}, [])return (<div><button onClick={handleClick('wj', 18)}>点我</button></div>);
}export default App;
方式四:使用data attribute
import React, { MouseEvent } from "react";function App() {const handleClick = (event: MouseEvent<HTMLButtonElement>) => {console.log(event)const name = event.currentTarget.getAttribute('data-name')console.log(name)}return (<div><button data-name="from data attribute wj" onClick={handleClick}>点我</button></div>);
}export default App;
参考
3 Ways Of Passing Multiple Parameters To The OnClick Handler In React
Pass event and parameter onClick in React