HarmonyOS Span的封装问题

我希望可以封装单独的Span组件,用于在不同的text中解析表情包、解析话题等等。

问题:测试发现,如果是在List中,按下面代码封装Span,Span显示不出来。如果不是List中的话,是正常的。

测试代码

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State array: Array<String> = new Array()

  aboutToAppear(): void {
    let i = 0
    while (i < 30) {
      this.array.push("测试" + i)
      i++
    }
  }

  build() {
    Column() {
      List() {
        ForEach(this.array, (item: string, index: number) => {
          ListItem() {
            Text() {
              TestSpan({ content: item })
            }.height(50)
          }
        })
      }
    }
    .height('100%')
    .width('100%')
  }
}

@Component
struct TestSpan {
  @Prop
  content: string = ""
  build() {
    Span(this.content)
  }
}
HarmonyOS
2025-01-09 14:18:04
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

Span只能作为Text、ContainerSpan的子组件显示,使用自定义组件包裹Span会受渲染时机影响导致显示异常,建议不要单独封装Span

本身Span只支持设置一些文本属性,可以考虑通过attributeModifier进行封装,参考:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-universal-attributes-attribute-modifier-V5

//demo.ets
class MySpanModifier implements AttributeModifier<SpanAttribute> {
  //...
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State array: Array<String> = new Array()

  aboutToAppear(): void {
    console.log('start')
    let i = 0
    while (i < 10) {
      this.array.push("测试" + i)
      i++
    }
  }

  build() {
    Column() {
      List() {
        ForEach(this.array, (item: string, index: number) => {
          ListItem() {
            Text() {
              ForEach(this.array,(item:string)=>{
                Span(item).attributeModifier(new MySpanModifier())
              })
            }.height(50)
          }
        })
      }
    }
    .height('100%')
    .width('100%')
  }
}
分享
微博
QQ
微信
回复
2025-01-09 17:00:17
相关问题
HarmonyOS Text中Span显示问题
797浏览 • 1回复 待解决
HarmonyOS Text/Span使用问题
679浏览 • 1回复 待解决
HarmonyOS Span标签样式问题
606浏览 • 1回复 待解决
HarmonyOS 组件封装问题
350浏览 • 1回复 待解决
HarmonyOS AttributeModifier封装bindPop问题
130浏览 • 1回复 待解决
HarmonyOSAxios封装使用问题
926浏览 • 1回复 待解决
HarmonyOS 关于rcp请求封装问题
405浏览 • 1回复 待解决
HarmonyOS 关于页面架构封装问题
343浏览 • 1回复 待解决
HarmonyOS 使用Text里套Span标签使用问题
734浏览 • 1回复 待解决
HarmonyOS 自定义弹窗封装问题
366浏览 • 1回复 待解决
HarmonyOS Span属性设置失效
225浏览 • 1回复 待解决
HarmonyOS 自定义弹框封装问题
386浏览 • 1回复 待解决
HarmonyOS Text中ImageSpan和Span
875浏览 • 1回复 待解决
HarmonyOS TextSpan不支持align
265浏览 • 1回复 待解决
HarmonyOS Text内部Span宽度设置无效
310浏览 • 1回复 待解决
HarmonyOS 如何给span背景设置padding
184浏览 • 1回复 待解决
HarmonyOS http请求封装
520浏览 • 1回复 待解决
HarmonyOS 底层网络库封装
379浏览 • 1回复 待解决