如何在反应按钮上正确使用更改功能并且没有任何未使用的变量
How to properly use a change function on react button and not have any unused variables
我想要一个基本按钮,我可以在其中将 type
传递给单击时的函数。但是,我想在函数中没有 event
的情况下执行此操作,因为我确实遇到了 linting 错误 — event is definied but never used
。
const Test: React.FC = () => {
const [state, setState] = useState(null);
const handleClick = (type: string) => (event: object) => {
switch (type) {
case 'CASE_1':
doSomething(state);
break;
default:
return;
}
};
return (
<button onClick={handleClick('CASE_1')}>CLICK ME</button>
)
}
解决关于 TypeScripts 内置 linter 的问题:
- 在未使用的参数名称前加上下划线:
(_event: object) => {
Parameters declaration with names starting with _
are exempt from the unused parameter checking.
- 您还可以使用
noUnusedParameters
标志在您的 TypeScript 配置中全局禁用未使用的参数警告。
一般来说,任何 linter 都应该通过完全省略参数来静音:() => {...
如果使用参数从 TypeScript 调用此函数,编译器(可能还有其他 linter)会在调用站点抱怨无关参数。
但是因为它只被 React 调用,所以不会发生这种情况。
我想要一个基本按钮,我可以在其中将 type
传递给单击时的函数。但是,我想在函数中没有 event
的情况下执行此操作,因为我确实遇到了 linting 错误 — event is definied but never used
。
const Test: React.FC = () => {
const [state, setState] = useState(null);
const handleClick = (type: string) => (event: object) => {
switch (type) {
case 'CASE_1':
doSomething(state);
break;
default:
return;
}
};
return (
<button onClick={handleClick('CASE_1')}>CLICK ME</button>
)
}
解决关于 TypeScripts 内置 linter 的问题:
- 在未使用的参数名称前加上下划线:
(_event: object) => {
Parameters declaration with names starting with
_
are exempt from the unused parameter checking.
- 您还可以使用
noUnusedParameters
标志在您的 TypeScript 配置中全局禁用未使用的参数警告。
一般来说,任何 linter 都应该通过完全省略参数来静音:() => {...
如果使用参数从 TypeScript 调用此函数,编译器(可能还有其他 linter)会在调用站点抱怨无关参数。
但是因为它只被 React 调用,所以不会发生这种情况。