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

React文本框编辑JSON时格式失效报错问题咨询

解决React中JSON编辑textarea格式错误无法继续编辑的问题

问题核心在于你当前的state存储的是解析后的JSON对象,每次编辑时强制用JSON.parse转换用户输入,一旦格式非法就抛出异常,导致state无法更新,textarea被锁定在之前的合法值上。

解决方案

把state改成存储原始字符串形式的JSON,让textarea直接绑定用户输入的原始内容,不强制实时解析,仅在需要时做格式验证(可选)。

修改后的完整代码

import "./styles.css";
import { useState } from "react";

export default function App() {
  // 初始state转为JSON字符串数组,保持格式化后的缩进
  const [value, setValue] = useState([
    JSON.stringify(
      {
        Id: 1,
        Action: "CONCAT",
        Targets: [
          'eval("',
          'link=\\"',
          "$Link",
          '\\";sp=link.split(\\"__requestHeader=\\");sp[0]")'
        ],
        Result: "$str_Link"
      },
      null,
      "\t"
    ),
    JSON.stringify(
      {
        Id: 2,
        Action: "CONCAT",
        Targets: [
          'eval("',
          'link=\\"',
          "$Link",
          '\\";sp=link.split(\\"__requestHeader=\\");sp[1]")'
        ],
        Result: "$str_Header"
      },
      null,
      "\t"
    )
  ]);

  // 存储每个textarea的错误状态(可选)
  const [errorStates, setErrorStates] = useState(new Array(value.length).fill(null));

  const valueHandleChange = (e, index) => {
    const inputValue = e.target.value;
    const newValue = [...value];
    newValue[index] = inputValue;
    setValue(newValue);

    // 可选:验证JSON格式并更新错误提示
    try {
      JSON.parse(inputValue);
      // 格式合法,清除错误提示
      setErrorStates(prev => {
        const newErrors = [...prev];
        newErrors[index] = null;
        return newErrors;
      });
    } catch (err) {
      // 格式错误,设置错误提示
      setErrorStates(prev => {
        const newErrors = [...prev];
        newErrors[index] = "JSON格式不正确";
        return newErrors;
      });
    }
  };

  return (
    <div className="App">
      {value.map((item, index) => (
        <div key={index}>
          <textarea
            spellCheck={false}
            onChange={(e) => valueHandleChange(e, index)}
            value={item}
            rows={8}
            cols={80}
          ></textarea>
          {/* 显示错误提示(可选) */}
          {errorStates[index] && <p style={{ color: "red", margin: "5px 0" }}>{errorStates[index]}</p>}
        </div>
      ))}
    </div>
  );
}

关键修改点

  1. state存储方式变更:从解析后的对象数组改为JSON字符串数组,确保用户输入的原始内容能被实时保存。
  2. onChange逻辑简化:直接保存用户输入的字符串,不再强制JSON.parse,避免格式错误时的异常阻塞。
  3. 可选格式验证:添加错误状态数组,在用户输入时尝试解析JSON,格式错误时显示提示,但不阻止编辑操作。

这样修改后,即使输入非法JSON,textarea也能正常显示用户输入的内容,用户可以继续编辑修正格式问题。

内容的提问来源于stack exchange,提问作者Nghĩa Phạm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:45:42