Stencil JS - 使用 Prop 值启动状态变量?

Stencil JS - Initiate a State variable with a Prop value?

在我的 Stencil 组件中,我想用传递的 prop 值启动我的状态变量。如何在 Stencil 中做到这一点?

我试过将值赋给 componentWillLoad 中的状态变量,但它不起作用。

@Prop() passedVal
@State() someVal = ??

我是Stencil的新手,我是VueJS出身,所以请多多包涵我这个看似菜鸟的问题

最好观察道具的变化,然后更新状态。

@Component({ tag: 'my-comp' })
export class MyComp {
  @Prop() foo: string;

  @State() bar: string;

  @Watch('foo')
  onFooChange() {
    this.bar = this.foo;
  }

  componentWillLoad() {
    this.onFooChange();
  }

  render() {
    return this.foo + this.bar;
  }
}

您可以在 componentWillLoad 中调用您的 watcher 方法,因为只有在组件加载后才会开始监视。

对于以后的人来说,@Watch 将要监视的 @Prop 变量的名称作为参数。任何时候该 prop 的值发生变化,由 @Watch 装饰的函数将以 newValueoldValue 作为参数被调用。

export class SomeClass{
  @Prop() isValid: boolean = true;
  @Watch("isValid")
  watchHandler(newValue, oldValue) {
    console.log("newValue: ", newValue, "oldValue: ", oldValue);
    this.isValid = newValue;
  }
}