[英]Change StencilJS component on window scroll
Is it possible to change styling of a StencilJS component when the window it is used on is scrolled?当滚动使用它的窗口时,是否可以更改 StencilJS 组件的样式?
I have the following code:我有以下代码:
import { h } from '@stencil/core';
import { Component, Prop } from '@stencil/core'
@Component({
tag: 'example-component',
styleUrl: './example-component.css',
shadow: true
})
export class ExampleComponent{
@Prop() some_text: string;
render(){
return [
<p class="someText">{this.some_text}</p>,
<script type="text/javascript">
var text = document.querySelector(".someText");
window.addEventListener('scroll', function(e) {
text.classList.add("newClassName")
});
</script>
]
}
}
And it doesn't work.它不起作用。 I want to add a new class to the text when the window is scrolled, how can I achieve this?
我想在滚动窗口时向文本添加一个新类,我该如何实现?
Your JavaScript code should no be part of what's rendered.您的 JavaScript 代码不应成为呈现内容的一部分。
Didn't tried out the following code but a start could looks like the following:没有尝试以下代码,但开始可能如下所示:
import { h, Listen, State, Component, Prop } from '@stencil/core';
@Component({
tag: 'example-component',
styleUrl: './example-component.css',
shadow: true
})
export class ExampleComponent {
@Prop() some_text: string;
@State() myClass: string | undefined = undefined;
@Listen('scroll', {target: 'window'})
onScroll() {
this.myClass = 'newClassName';
}
render() {
return <p class={this.myClass}>{this.some_text}</p>
}
}
For references you could check the following part of the Stencil doc.对于参考,您可以查看 Stencil 文档的以下部分。
Using JSX: https://stenciljs.com/docs/templating-jsx使用 JSX: https ://stenciljs.com/docs/templating-jsx
Internal state: https://stenciljs.com/docs/state内部状态: https : //stenciljs.com/docs/state
Events: https://stenciljs.com/docs/events活动: https : //stenciljs.com/docs/events
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.