我正在尝试学习 stencilJS,我正在开发具有自动对焦输入字段的组件。
我在 index.html 中调用了两次组件,我遇到了奇怪的问题,第二个渲染组件正在自动对焦第一个渲染组件。
并且组件不是每次都以相同的顺序呈现,最后呈现它的输入字段的组件将具有剩余的焦点,不会获得自动对焦。
下面附上代码,请帮我整理一下。
索引.html
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" />
<title>Stencil Component Starter</title>
<script type="module" src="/build/testing.esm.js"></script>
<script nomodule src="/build/testing.js"></script>
</head>
<body>
<search-input data-test-id="test-two" place-holder="Search" value=""></search-input>
<search-input data-test-id="test-three" place-holder="Search" value=""></search-input>
</body>
</html>
搜索插件.tsx
import { Component, h, Prop, Event, EventEmitter } from '@stencil/core';
@Component({
tag: 'search-input',
styleUrl: 'search-input.css',
shadow: true,
})
export class SearchInput {
private searchInput: HTMLInputElement;
@Prop() value = "";
@Prop() dataTestId!: string;
@Prop() placeHolder: string = "Search";
@Event() clearSearch: EventEmitter;
@Event() searchRequest: EventEmitter;
protected componentDidLoad() {
this.searchInput.focus();
}
render() {
return (
<div data-test-id={this.dataTestId} class="items-center flex bg-white border-solid rounded-sm border-gray-300 box-border text-xl border-1 pl-15 pr-12 py-9">
<input
type="text"
ref={el => (this.searchInput = el as HTMLInputElement)}
data-test-id={`${this.dataTestId}-search-input`}
class="focus:outline-none border-0 flex-grow w-full pl-15"
value={this.value}
placeholder={this.placeHolder}
/>
</div>
);
}
}