ts-component-states-prop.md 2.7 KB
Newer Older
Z
zengyawen 已提交
1
# @Prop<a name="ZH-CN_TOPIC_0000001157388853"></a>
Z
zengyawen 已提交
2

Z
zengyawen 已提交
3
**@Prop与@State**有相同的语义,但初始化方式不同。**@Prop**装饰的变量必须使用其父组件提供的**@State**变量进行初始化,允许组件内部修改**@Prop**变量,但更改不会通知给父组件,即**@Prop**属于单向数据绑定。
Z
zengyawen 已提交
4

Z
zengyawen 已提交
5
**@Prop**状态数据具有以下特征:
Z
zengyawen 已提交
6

Z
zengyawen 已提交
7 8 9 10
-   **支持简单类型:**仅支持number、string、boolean简单类型;
-   **私有:**仅在组件内访问;
-   **支持多个实例:**一个组件中可以定义多个标有**@Prop**的属性;
-   **创建自定义组件时将值传递给@Prop变量进行初始化:**在创建组件的新实例时,必须初始化所有@Prop变量,不支持在组件内部进行初始化。
Z
zengyawen 已提交
11

Z
zengyawen 已提交
12
## 示例<a name="section599175705019"></a>
Z
zengyawen 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

```
@Entry
@Component
struct ParentComponent {
    @State countDownStartValue: number = 10 // 10 Nuggets default start value in a Game
    build() {
        Column() {
            Text(`Grant ${this.countDownStartValue} nuggets to play.`)
            Button() {
                Text('+1 - Nuggets in New Game')
            }.onClick(() => {
                this.countDownStartValue += 1
            })
            Button() {
                Text('-1  - Nuggets in New Game')
            }.onClick(() => {
                this.countDownStartValue -= 1
            })

            // when creatng ChildComponent, the initial value of its @Prop variable must be supplied
            // in a named constructor parameter
            // also regular costOfOneAttempt (non-Prop) variable is initialied
            CountDownComponent({ count: this.countDownStartValue, costOfOneAttempt: 2})
        }
    }
}

@Component
struct CountDownComponent {
    @Prop count: number
    private costOfOneAttempt: number

    build() {
        Column() {
            if (this.count > 0) {
                Text(`You have ${this.count} Nuggets left`)
            } else {
                Text('Game over!')
            }

            Button() {
                Text('Try again')
            }.onClick(() => {
                this.count -= this.costOfOneAttempt
            })
        }
    }
}
```

Z
zengyawen 已提交
64 65
在上述示例中,当按“+1”或“-1”按钮时,父组件状态发生变化,重新执行**build**方法,此时将创建一个新的**CountDownComponent**组件。父组件的**countDownStartValue**状态属性被用于初始化子组件的**@Prop**变量,当按下子组件的“Try again”按钮时,其**@Prop**变量**count**将被更改,**CountDownComponent**重新渲染。但是**count**值的更改不会影响父组件的**countDownStartValue**值。

66
>![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** 
Z
zengyawen 已提交
67
>创建新组件实例时,必须初始化其所有**@Prop**变量。
Z
zengyawen 已提交
68