You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 of state.name lets 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 helperText once and reusing it for error and color makes the code cleaner and more efficient.
  • Preserve Existing State: Spreading ...prevState[name] ensures we don't overwrite other properties in that state entry (like defaultValue in your testName example).

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 12:47:38