하모니에서 개발한 Text 컴포넌트 사용

TextInput 및 TextArea는 입력 상자 구성 요소로 일반적으로 주석 영역 입력, 채팅 상자 입력, 양식 입력 등과 같은 사용자 입력 작업에 응답하는 데 사용됩니다. 또한 다른 구성 요소와 결합하여 기능적 페이지를 구축할 수도 있습니다. , 로그인 및 등록 페이지 등.

이미지 출처: 다크호스 프로그래머

텍스트 구성 요소 사용:

텍스트 구성 요소를 표시하는 방법에는 두 가지가 있습니다. 하나는 문자열이고 다른 하나는 지정된 문자열 형식으로 문자열을 읽는 것입니다!

한정자에 따라 지정된 국어를 전환할 수 있어 장치의 국유화를 실현할 수 있다는 것을 알 수 있습니다!

Textinput 구성 요소 사용:

TextInput에는 일반 기본 입력 모드, 비밀번호 비밀번호 입력 모드, 이메일 주소 입력 모드, 숫자 순수 숫자 입력 모드, 전화번호 전화번호 입력 모드 등 5가지 선택 유형이 있습니다.

입력이 없을 때 프롬프트 텍스트를 설정합니다.

TextInput({placeholder:'나는 프롬프트 텍스트입니다'})

입력 상자의 현재 텍스트 내용을 설정합니다.

입력 상자의 배경색을 변경하려면 backgroundColor를 추가하세요.

소스코드 부분은 다음과 같습니다.

@Entry
@Component
struct Index2 {
  @State imageWidth: number = 100

  build() {
    Column() {
      Row(){
        Image($r('app.media.icon'))
          .width(this.imageWidth)//控制图片的大小
      }
      .width('100')
      .height("100")
      .justifyContent(FlexAlign.Center)

      Row(){
        Text($r('app.string.width_label'))
          .fontSize(20)
          .fontWeight(FontWeight.Bold)

        TextInput({text: this.imageWidth.toFixed(0)})
          .width(150)
          .backgroundColor('#FFF')
          .type(InputType.Number)
          .onChange( value => {    //获取输入
            this.imageWidth = parseInt(value)
          })
      }
      .width('100%')
      .padding({left: 14, right: 14})
      .justifyContent(FlexAlign.SpaceBetween)

      Divider()
        .width('91%')

      Row(){
        Button('缩小')
          .width(80)
          .fontSize(20)
          .onClick(() => {
            if(this.imageWidth >= 10){
              this.imageWidth -= 10
            }
          })

        Button('放大')
          .width(80)
          .fontSize(20)
          .onClick(() => {
            if(this.imageWidth < 300){
              this.imageWidth += 10
            }
          })
      }
      .width('100%')
      .margin({ top: 35, bottom: 35 })
      .justifyContent(FlexAlign.SpaceEvenly)


      Slider({
        min: 100,
        max: 300,
        value: this.imageWidth,
        step: 10,
      })
        .width('100%')
        .blockColor('#36D')
        .trackThickness(5)
        .showTips(true)
        .onChange(value => {
          this.imageWidth = value
        })
    }
    .width('100%')
    .height('100%')
  }
}

텍스트 상자는 주로 사용자가 입력한 정보를 얻고, 해당 정보를 업로드할 데이터로 처리하고, onChange 이벤트를 바인딩하여 입력 상자에서 변경된 내용을 얻는 데 사용됩니다.

시나리오 예

양식 제출, 사용자 로그인/등록 페이지, 사용자 로그인 또는 등록 입력 작업에 사용됩니다.

TextInput()
  .onChange((value: string) => {
    console.info(value);
  })
  .onFocus(() => {
    console.info('获取焦点');
  })

TextArea (이 구성 요소는 API 버전 7부터 지원됩니다.)

여러 줄의 텍스트 입력 상자 구성 요소는 입력 텍스트 내용이 구성 요소의 너비를 초과하면 자동으로 줄 바꿈되어 표시됩니다.

지원공통 이벤트(공통 이벤트에는 너비, 높이, 내부 및 외부 여백이 포함됩니다.) 외에도 다음도 지원합니다. 이벤트:

onCopy(callback:(value: string) => void) 입력 상자 내부 영역을 길게 눌러 클립보드를 띄운 후, 클립보드 복사 버튼을 클릭하면 이 콜백이 실행됩니다. CopyOptions.None이 설정되면 현재 TextArea의 텍스트를 복사하거나 잘라낼 수 없으며 붙여넣기만 지원됩니다.

onCut(callback:(value: string) => void) 입력 상자 내부 영역을 길게 눌러 클립보드를 띄운 후 클립보드 잘라내기 버튼을 클릭하면 이 콜백이 실행됩니다.

onPaste(callback:(value: string) => void) 입력 상자 내부 영역을 길게 눌러 클립보드를 띄운 후, 클립보드 붙여넣기 버튼을 클릭하면 이 콜백이 실행됩니다.

caretPosition(value: number): void 커서의 위치를 ​​설정할 수 있습니다.

샘플 코드는 다음과 같습니다.

// xxx.ets
@Entry
@Component
struct TextAreaExample {
  @State text: string = ''
  controller: TextAreaController = new TextAreaController()

  build() {
    Column() {
      TextArea({
        placeholder: 'The text area can hold an unlimited amount of text. input your word...',
        controller: this.controller
      })
        .placeholderFont({ size: 16, weight: 400 })//设置placeholder文本样式,包括字体大小,字体粗细,字体族,字体风格。目前仅支持默认字体族。
        .width(336)
        .height(56)
        .margin(20)
        .fontSize(16)
        .fontColor('#182431')
        .backgroundColor('#FFFFFF')
        .onChange((value: string) => {
          this.text = value
        })
      Text(this.text)
      Button('Set caretPosition 1')
        .backgroundColor('#007DFF')//背景颜色
        .margin(15)//边距
        .onClick(() => {
          // 设置光标位置到第一个字符后
          this.controller.caretPosition(1)
        })
    }.width('100%').height('100%').backgroundColor('#F1F3F5')
  }
}

위 정보는 공식 홈페이지 매뉴얼에서 가져온 것입니다.

추천

출처blog.csdn.net/Helloorld_1/article/details/134823290