最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass @Prop() function in custom web component in stenciljs - Stack Overflow

programmeradmin4浏览0评论

How Can I pass @Prop() as function that toggle events for the ponent in Stencil.js ?

@Prop() myFunction() {
         console.log("Hello World!")
         }

and place it in

<my-ponent onClick={myFunction()}></my-ponent>

How Can I pass @Prop() as function that toggle events for the ponent in Stencil.js ?

@Prop() myFunction() {
         console.log("Hello World!")
         }

and place it in

<my-ponent onClick={myFunction()}></my-ponent>
Share Improve this question edited Jan 28, 2019 at 20:30 Siddharth Thakor asked Jan 28, 2019 at 20:11 Siddharth ThakorSiddharth Thakor 1563 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

That is not the correct way to handle events in you web ponent. In order to handle onClick event on your web ponent you must implement a click listener within your ponent by decorating it with @Listen decorator.

https://stenciljs./docs/events Events - Stencil

@Listen('click')
onClickHandler(event) {
// Do something
}

In case if you want your user to write the code for what should happen on click of your ponent, you need to emit the click event from your ponent and the user should implement a listener for that

https://stenciljs./docs/events Events - Stencil

In order to pass a function to your ponent you will just pass the function reference. In your example, if you exposed a myFunction Prop then all you have to do in the parent render function is to pass the function. For example:

// parent render function
render() { 
  const funcReference = () => { console.log('click') };
  return (<my-ponent myFunction={funcReference}></my-ponent>);
}

In MyComponent you will wire the function to the onClick handler of the element that should run the function. For example:

// MyComponent render function
render() {
  return (<div>
            <button onClick={this.myFunction}>Click Me!</button>
          </div>);
}

As explained by the previous answer, if you want to notify a parent ponent about a click then you will use an EventEmitter in the child ponent and a @Listen function on the parent.

发布评论

评论列表(0)

  1. 暂无评论