一、实现用户名检验
条件渲染 、生命周期
1.规定用户名长度
2.限定使用的数字及字母(涉及正则表达)
// 导出方式直接从文件夹
import MyInput from "../common/commons/myInput"
@Entry
@Component
/*
组件可以基于struct实现,组件不能有继承关系,struct可以比class更加快速的创建和销毁。
*/
struct Index {
// 此处可以不赋值
// 赋值的目的方便preview的时候检查
@State username :string = "1652e1"
@State password :string = "456451"
private username_reg = /^[A-Za-z0-9]{5,8}$/;
onPageShow(){
let test_res = this.username_reg.test(this.username)
console.info(test_res)
}
build() {
Flex({direction:FlexDirection.Column,
justifyContent:FlexAlign.Center,
alignItems:ItemAlign.Center}){
Text("登录")
.fontSize(40)
.fontWeight(700)
// 用户名要求
//1、用户名至少五位
//2、正则匹配
// if (this.username.length<5){
// Text("用户名至少五位")
// .fontSize(13)
// .fontWeight(700)
// .fontColor("#ff0000")
// .width("80%")
// }
// 用生命周期改进
if (!this.username_reg.test(this.username)){
Text("用户名必须5-8位,英文字母和数字组合")
.fontSize(13)
.fontWeight(700)
.fontColor("#ff0000")
.width("80%")
}
// 组件封装,完成父组件向子组件传参
MyInput({placeHolder:"请输入用户名",inputValue:$username})
/*
placeHolder:"请输入用户名" 实现父组件向子组件传递 :请输入用户名
inputValue:$username 子组件把监听得到的数据传到父组件
下列代码再使用传回来的数据
Text(this.username)
.fontSize(30)
.fontWeight(700)
.width("80%")
该处未对数据进行校验,只是简单展示
*/
MyInput({placeHolder:"请输密码 ",inputValue:$password})
Button("进入app")
}.width("100%")
.height("100%")
.border({width:15,color:"#000"})
}
}
二、模拟真机演示
1.演示中当输入用户名不符合要求是有提示
2.输入符合要求是提示的红色字体消失