React函数组件中规避内联箭头函数不良实践:带参数事件回调的处理方法
Great question! You’re correct that inline arrow functions can lead to unnecessary function re-creation on each render (which might trigger extra re-renders for memoized child components). While for native elements like <input> this often doesn’t cause noticeable issues, it’s good practice to avoid it when possible. Here are a few clean solutions for your CustomInput scenario:
1. Split into Separate Handler Functions
The simplest approach is to create dedicated functions for each event, eliminating the need to pass parameters altogether. This keeps your code readable and avoids inline functions:
import { useState } from 'react'; const CustomInput = () => { const [focused, setFocused] = useState(false); const handleFocus = () => { // Add your condition checks here setFocused(true); }; const handleBlur = () => { // Add your condition checks here setFocused(false); }; return ( <input onFocus={handleFocus} onBlur={handleBlur} /> ); };
This works perfectly for your use case since onFocus and onBlur inherently signal the state you need—no extra parameters required.
2. Use a Single Handler with Event Type Detection
If you want to avoid duplicating logic between focus and blur handlers, you can use a single function that checks the event type to determine the focus state:
import { useState, useCallback } from 'react'; const CustomInput = () => { const [focused, setFocused] = useState(false); // useCallback caches the function to prevent unnecessary re-creations const handleFocusChange = useCallback((e) => { const isFocused = e.type === 'focus'; // Add your condition checks here setFocused(isFocused); }, []); return ( <input onFocus={handleFocusChange} onBlur={handleFocusChange} /> ); };
Using useCallback ensures the handler function stays stable across renders, which is helpful if you ever wrap this input in a memoized component.
3. Stable Handlers with useCallback (For Cases Needing Explicit Parameters)
If you ever need to pass custom parameters (like an ID or additional data) instead of relying on the event itself, wrap your handler with useCallback to keep it stable. While you’ll still use an inline arrow to pass the parameter, the underlying handler won’t re-create on every render:
import { useState, useCallback } from 'react'; const CustomInput = () => { const [focused, setFocused] = useState(false); // Cached handler that accepts a parameter const handleFocusUpdate = useCallback((isFocus) => { // Add your condition checks here setFocused(isFocus); }, []); return ( <input onFocus={() => handleFocusUpdate(true)} onBlur={() => handleFocusUpdate(false)} /> ); };
This is a safe middle ground: the inline arrow creates a new function each render, but since it’s only wrapping a stable cached handler, it won’t cause issues for most use cases (especially with native DOM elements).
内容的提问来源于stack exchange,提问作者BeHappy

