开发者在使用TextInput组件时,对背景的设置有以下几个经典场景,分别该如何实现?
去除TextInput默认背景色也可使用此方案。
@Entry
@Component
struct Index {
controller: TextInputController | undefined;
@State message: string = '';
build() {
Column() {
Column() {
TextInput({ text: this.message, placeholder: 'input your word...', controller: this.controller })
.borderWidth(1)
.backgroundColor('#5AADA0')
}
.width('86%')
.backgroundColor('#0A59F7') // 设置Column的背景色来填充TextInput组件外部的背景色。
}
.width('100%')
.height('100%')
.padding({top:10})
}
} 效果预览:

@Entry
@Component
struct Scene2 {
@State text: string = '';
controller: TextInputController = new TextInputController();
@State color: string = '#fdecc949';
build() {
Column() {
TextInput({ text: this.text, placeholder: 'input your word...', controller: this.controller })
.placeholderColor(Color.Grey)
.placeholderFont({ size: 14, weight: 400 })
.caretColor(Color.Blue)
.width('95%')
.height(40)
.margin(20)
.fontSize(14)
.fontColor(Color.Black)
.backgroundColor(this.color)
.onChange((value: string) => {
this.text = value;
if (this.text.length > 0) { // 判断是否有内容输入,大于零则有,否则没有
this.color = '#ff0fe7d5';
} else {
this.color = '#fdecc949';
}
})
}
}
} 效果预览:

Q:使用多态样式动态修改TextInput组件背景色,为什么没有效果?
A:多态样式仅支持通用属性。如果多态样式不生效,则该属性可能为组件的私有属性,例如:fontColor、TextInput组件的backgroundColor等。此时,可以通过动态属性设置来解决此问题。
Q:使用background设置背景如何配置扩展到的安全区的范围?
A:background从API 20开始,新增了背景向父组件的安全区扩展的能力,通过BackgroundOptions中的ignoresLayoutSafeAreaEdges参数可以设置扩展到的安全区的范围,如:LayoutSafeAreaEdge.TOP上方区域。