您可以使用第三方库react-json-view来实现此操作。首先,您需要安装它:

npm install react-json-view

然后,您可以在函数组件中导入它:

import React, { useState } from 'react';
import ReactJson from 'react-json-view';
import { Input } from 'antd';

const { TextArea } = Input;

const MyComponent = () => {
  const [json, setJson] = useState('');

  const handleJsonChange = e => {
    setJson(e.target.value);
  };

  return (
    <>
      <TextArea rows={10} value={json} onChange={handleJsonChange} />
      <ReactJson src={JSON.parse(json)} />
    </>
  );
};

在上面的代码中,我们使用useState来存储用户输入的JSON字符串,然后使用ReactJson组件来将其格式化并高亮显示。

注意:在将JSON字符串传递给ReactJson之前,我们使用JSON.parse将其转换为JavaScript对象。这是必要的,因为ReactJson只接受JavaScript对象作为输入。

react函数组件中InputTextArea如何格式化高亮显示json

原文地址: https://www.cveoy.top/t/topic/byg3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录