React表格开发:如何通过字符串参数实现对象式State的通用onChange更新
Generic onChange Handler for Dynamic State Updates
Absolutely, you can create a reusable onChange handler by leveraging JavaScript's bracket notation to dynamically access and update your state properties based on the input's name attribute. Here's how to fix your approach and make it work smoothly:
Step 1: Update Your Generic InputChange Function
const InputChange = (e) => { const { value, name } = e.target; // Calculate helperText once to avoid redundant function calls const helperText = state[name].evaluateHelperText(value); const error = !!helperText; // Convert to boolean (true if helperText exists) const color = state[name].evaluateColor(value, error); setState(prevState => ({ ...prevState, [name]: { // Use bracket notation to target the dynamic state key ...prevState[name], // Preserve existing properties of this state entry helperText, focused: true, error, color } })); };
Step 2: Add the name Attribute to Your Input Components
Make sure each TextField/Autocomplete has a name attribute matching the corresponding key in your state (e.g., "runTimeStamp"):
<TextField name="runTimeStamp" onChange={InputChange} // Other props (use state.runTimeStamp.helperText, state.runTimeStamp.error, etc. for dynamic display) />
Key Fixes & Explanations
- Dynamic State Access: Using
state[name]instead ofstate.namelets you reference the correct state property using the input's name string. - Bracket Notation in setState:
[name]in the state update ensures we're modifying the right state entry (no more hardcoding "runTimeStamp"). - Avoid Redundant Work: Calculating
helperTextonce and reusing it forerrorandcolormakes the code cleaner and more efficient. - Preserve Existing State: Spreading
...prevState[name]ensures we don't overwrite other properties in that state entry (likedefaultValuein yourtestNameexample).
Note on State Structure
For this to work, any state entry used with this handler should have evaluateHelperText and evaluateColor functions defined (like your runTimeStamp entry). If some entries don't need validation, you can add a quick check in the handler to skip those steps if needed.
内容的提问来源于stack exchange,提问作者Victor Santos
相关产品推荐
相关产品推荐

