[英]Stencil does not re-render component when @state() property changes
Does anyone know why my component doesn't re-render when this.searchText
is cleared in clearSearchText()
?有谁知道为什么我的组件在
clearSearchText()
中清除this.searchText
时没有重新渲染?
Thanks in advance.提前致谢。
NOTE: I have already checked this related question but the answers don't work for me: stencil is not rerendeing component when @state() decorated property is changed注意:我已经检查过这个相关问题,但答案对我不起作用: 当 @state() 修饰属性发生更改时,模板不会重新渲染组件
import { Component, h, Prop, State } from '@stencil/core';
import { faMagnifyingGlass, faX } from '@fortawesome/free-solid-svg-icons';
@Component({
tag: 'search',
styleUrl: 'search.scss',
shadow: true,
})
export class Search {
@State() searchText: string = null;
private handleSearchTextChanged(event) {
this.searchText = event.target.value;
}
/**
* This prop points to the memory address of the *real* search function
* on the parent of this component.
*/
@Prop() doSearch: Function;
@Prop() placeholderText: string;
@Prop() buttonText: string;
private handleSearchButtonPressed() {
this.doSearch(this.searchText);
}
private handleEnterPressed(ev: KeyboardEvent) {
if (ev.key === 'Enter') {
this.doSearch(this.searchText);
}
}
private clearSearchText = () => {
this.searchText = ''; // this does NOT trigger a re-render
console.log('got here'); // this is printed
}
render() {
return (
<div class="container">
<h2>Find a Charity</h2>
<div class="search-box">
<svg xmlns="http://www.w3.org/2000/svg" class="icon" viewBox="0 0 512 512">
<path d={faMagnifyingGlass.icon[4].toString()} />
</svg>
<input type="text" placeholder={this.placeholderText} onInput={event => this.handleSearchTextChanged(event)} onKeyDown={event => this.handleEnterPressed(event)} />
<svg xmlns="http://www.w3.org/2000/svg" class="icon" id="x-icon" viewBox="0 0 512 512" onClick={() => this.clearSearchText()}>
<path d={faX.icon[4].toString()} />
</svg>
</div>
<button onClick={() => this.handleSearchButtonPressed()}>{this.buttonText}</button>
</div>
);
}
}
I just created a quick demo: https://studio.webcomponents.dev/edit/MBPPrzr13SM3y37LEzog我刚刚创建了一个快速演示: https://studio.webcomponents.dev/edit/MBPPrzr13SM3y37LEzog
The state property is actually cleared and the component is rerendered, the problem is that you're not assigning the new value to the input. state 属性实际上被清除并且组件被重新渲染,问题是您没有将新值分配给输入。 To do that, add a
value
property to the text input:为此,向文本输入添加一个
value
属性:
render() {
return (
// ...
<input type="text" value={this.searchText} placeholder={this.placeholderText} onInput={event => this.handleSearchTextChanged(event)} onKeyDown={event => this.handleEnterPressed(event)} />
// ...
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.