首页 > 解决方案 > Stencil JS - 使用 Prop 值启动状态变量?

问题描述

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

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

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

我是 Stencil 的新手,我来自 VueJS,所以请忍受我这个看似无聊的问题。

标签: javascriptstenciljs

解决方案


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

@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因为观察只会在组件加载后开始。


推荐阅读