@uiw/react-json-view 修改文本省略号、自定义节点内容展示(以null节点、数组节点为例)

183 阅读2分钟

@uiw/react-json-view是一个用于显示和编辑JavaScript数组及JSON对象的React组件,但是官网对于自定义节点内容展示的写的很晦涩,这篇文章是自己根据源码的踩坑后的心得,期望能帮到使用的人

修改文本截断后的省略号

当文本超过设置shortenTextAfterLength数值时,会显示...,点击才可以显示完整的内容,但是有些用户可能不知道要点击,所以需要优化一下~ 新版本(2.0)提供了开箱即用的参数stringEllipsis来修改(ts类型不对可忽略)

/** When the text exceeds the length, `...` will be displayed. Currently, this `...` can be customized. @default "..." */ 
{
    stringEllipsis?: number;
}

虽然官网写着是数字类型,但实际可以替换成想要的内容,比如我现在想显示成...显示更多,则可以修改

  <JsonView
    shortenTextAfterLength={5}
    stringEllipsis={'...显示更多'}
  >

ps:如果是低版本可按照下面的说明尝试修改JsonView.Ellipsis

自定义节点内容展示

该库在默认展示内容时,有一些跟常见json不太符合的样式:

  1. 当传入的数组值为null时(比如{a:null}),该组件值为空白,此时你可通过自定义JsonView.Null组件修改
  2. 默认的数组显示,会显示索引+分号(比如0:'数组值'),可通过自定义JsonView.KeyName组件修改key,通过JsonView.Colon修改分号 image.png

每个自定义组件都会有一个render参数,比如

    <JsonView.Null
      render={(props, result) => {
        if (result.value === null) {
          return <span {...props}>{result.value + ''}</span>
        }
      }}
    />

核心就是根据render函数的propsstyle去自定义我们的渲染内容,两个参数的含义:

  • porps是react组件的相关参数,包含childrenclassNamestyle等参数
  • result是当前这个自定义组件的相关数据,比如JsonView.Null就有 keyNamevalue等属性,而其他显示组件比如JsonView.KeyName则还有parentValue等属性

下面show my code:

完整例子

      <JsonView
        value={json}
        displayDataTypes={false}
        displayObjectSize={false}
        enableClipboard={false}
        collapsed={false}
        shortenTextAfterLength={5}
        stringEllipsis={'...显示更多'}
      >
        <JsonView.Null
          render={(props, result) => {
            //值为空时
            if (result.value === null) {
              return <span {...props}>{result.value + ''}</span>
            }
          }}
        />
        <JsonView.KeyName
          render={(props, result) => {
            //数组不显示对应的索引 
            if (Array.isArray(result.parentValue)) {
               //不能返回null,这里用display: 'none' 去隐藏
              return (
                <span {...props} style={{ ...props.style, display: 'none' }}>
                  {result.keyName}
                </span>
              )
            }
          }}
        />
        <JsonView.Colon
          render={(props, result) => {
            //数组不显示对应的分号 :
            if (Array.isArray(result.parentValue)) {
             //不能返回null,这里用display: 'none' 去隐藏
              return (
                <span {...props} style={{ ...props.style, display: 'none' }}>
                  :
                </span>
              )
            }
          }}
        />
      </JsonView>
  )

效果

当传入数据为{"a":null, "b": ["val1","this is a loooooooooooooooooooooong text"]}

修改前

image.png

修改后

image.png