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
2 Answers
Reset to default 4That 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.