【HarmonyOS NEXT 】应用开发:ArkTS 父页面调用子组件调用实例 ...

打印 上一主题 下一主题

主题 1001|帖子 1001|积分 3003

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
SDK:5.0.0
DevEco Studio:5.0.3
Node.js:18.20.1
  子组件一:新建页面

1、创建页面:src > main > ets > pages > components > Child > index.ets
2、页面代码:
  1. @Component
  2. export struct Child {
  3.   @Prop name: string
  4.   @State message: string = '子组件一';
  5.   
  6.   build() {
  7.     Row() {
  8.       // 文本 函数名(参数)对象.方法名(参数) 枚举名.常量名
  9.       Text(this.message)
  10.         .fontSize(30) // 设置文本的文字大小
  11.         .fontWeight(FontWeight.Bold) // 设置文本的粗细
  12.         .fontColor(Color.Blue) // 设置文本的颜色
  13.         .alignRules({
  14.           center: { anchor: '__container__', align: VerticalAlign.Center },
  15.           middle: { anchor: '__container__', align: HorizontalAlign.Center }
  16.         })
  17.     }
  18.   }
  19. }
复制代码
备注:
   1、吸收父组件的传参写法:@Prop name: string
2、在构造页面时前面要加上export,将代码抛出,否则父组件无法识别
  子组件二:与主组件在同一页面

1、与父组件路径:src > main > ets > pages > Parent > index.ets
2、页面代码
  1. @Component
  2. struct ChildTwo {
  3.   @Prop name: string
  4.   @State message: string = '子组件二';
  5.   build() {
  6.     Row() {
  7.       // 文本 函数名(参数)对象.方法名(参数) 枚举名.常量名
  8.       Text(this.message)
  9.         .fontSize(30)// 设置文本的文字大小
  10.         .fontWeight(FontWeight.Bold)// 设置文本的粗细
  11.         .fontColor(Color.Red)// 设置文本的颜色
  12.         .alignRules({
  13.           center: { anchor: '__container__', align: VerticalAlign.Center },
  14.           middle: { anchor: '__container__', align: HorizontalAlign.Center }
  15.         })
  16.     }
  17.   }
  18. }
复制代码
备注:
   1、吸收父组件的传参写法:@Prop name: string
2、在构造页面时前面要加上export,将代码抛出,否则父组件无法识别
  父组件

  1. import router from '@system.router';
  2. import { Child } from "../components/Child/index.ets"
  3. @Entry
  4. @Component
  5. struct Parent {
  6.   @State message: string = '父级页面';
  7.   // 构建界面
  8.   build() {
  9.     // 采用相对布局的容器,支持容器内部的子元素设置相对位置关系。子元素支持指定兄弟元素作为锚点,也支持指定父容器作为锚点,基于锚点做相对位置布局。下图是一个RelativeContainer的概念图,图中的虚线表示位置的依赖关系。
  10.     RelativeContainer() {
  11.       // Flex布局子项
  12.       Flex(){
  13.         Child().width("50%");
  14.         ChildTwo({name: "nameUse"}).width("50%");
  15.       }
  16.       // 文本 函数名(参数)对象.方法名(参数) 枚举名.常量名
  17.       Text(this.message)
  18.         .fontSize(50) // 设置文本的文字大小
  19.         .fontWeight(FontWeight.Bold) // 设置文本的粗细
  20.         .fontColor(Color.Blue) // 设置文本的颜色
  21.         .alignRules({
  22.           center: { anchor: '__container__', align: VerticalAlign.Center },
  23.           middle: { anchor: '__container__', align: HorizontalAlign.Center }
  24.         })
  25.     }
  26.   }
  27. }
复制代码
备注
   调用子组件方法:
import { Child } from “…/components/Child/index.ets”

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

罪恶克星

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表