Passing custom template to stencil component(将自定义模板传递给模具组件)
本文介绍了将自定义模板传递给模具组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用模具创建自定义组件以复制UI-select
。
该组件的用法如下:
let items = [{name:"Abc", age: 10}, {name:"Xyz", age: 10}];
let itemString = JSON.stringify(items);
<dropdown-search placeholder="Select User" item-string='${itemString}'>
</dropdown-search>
则组件定义为
import {
Component,
State,
Prop,
Element,
} from '@stencil/core';
@Component({
tag: 'dropdown-search',
})
export class DropdownSearch {
@Element() dropdownEl: HTMLElement;
@State() isOpen: boolean = false;
@State() items: any = [];
@Prop() itemString: string = '';
@Prop() placeholder: string = '';
componentDidLoad() {
try {
this.items = JSON.parse(this.itemString);
} catch(e) {}
}
onClickDropdownHandler = (e: UIEvent) => {
e.preventDefault();
this.toggleDropdown();
}
toggleDropdown = () => {
this.isOpen = !this.isOpen;
if (this.isOpen) {
window.setTimeout(
() => {
this.dropdownEl.querySelector('input').focus();
},
0,
);
}
}
renderOptions = () => {
if (!Array.isArray(this.items) || !this.items.length) {
return null;
}
return this.items.map((item) => (
<li
>
<a href="javascript:" title="{item.name}">
{item.name}
<small class="d-block">age: {item.age}</small>
</a>
</li>
));
}
render() {
let dropdownClassName = (this.isOpen ? 'open' : '');
return (
<form name="myForm">
<div class="form-group">
<div
class={`btn-group dropdown ${dropdownClassName}`}
>
<button
class="btn btn-default dropdown-toggle"
onClick={this.onClickDropdownHandler}
>
{this.placeholder}
</button>
<ul class="dropdown-menu" role="menu">
<li>
<div class="input-group input-group-search">
<input
class="form-control"
type="search"
/>
</div>
</li>
{this.renderOptions()}
</ul>
</div>
</div>
</form>
);
}
}
这些项目呈现得很好。由于用户可以传递自定义对象数组,因此我需要自定义选项模板。以便用户可以在使用组件时传递它。
现在,我对组件中的选项使用静态模板,如
<a href="javascript:" title="{item.name}">
{item.name}
<small class="d-block">age: {item.age}</small>
</a>
但我需要一种方法从我使用模板的位置传递该模板。我不能在那里使用槽,因为我在循环中运行的所有选项中使用相同的模板。
推荐答案
我是模具新手,但我只是尝试使用@Prop函数来执行此操作,它起作用了:
组件
@Component({
tag: 'dropdown-search',
styleUrl: 'dropdown-search.css',
shadow: true,
})
export class DropdownSearch {
// allow template function to be passed from outside
@Prop template!: (item: SelectItem) => any;
@State items!: SelectItem[] = [{name: 'dog'}, {name: 'cat'}, {name: 'elephant'}];
render() {
return (
<Host>
<p>Before Template</p>
{/* render the custom template here: *
沃梦达教程
本文标题为:将自定义模板传递给模具组件


基础教程推荐
猜你喜欢
- 我什么时候应该在导入时使用方括号 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 动态更新多个选择框 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 响应更改 div 大小保持纵横比 2022-01-01