首页 > 解决方案 > TypeError:无法在 stenciljs 中将类作为函数调用

问题描述

我试图在我的模板项目中使用 multiselect-react-dropdown 包,但是在渲染时我遇到了这个错误,我发现了很多反应解决方案,但没有任何真正的工作,任何人都可以帮助在 stenciljs 中做同样的事情。

import { Component, h, State } from '@stencil/core';
import { Multiselect } from 'multiselect-react-dropdown';


@Component({
    tag: 'ui-card',
    styleUrl: 'style.scss',
    shadow: true
})

export class UiCard {
    @State() state: any;

    constructor() {
        this.state = {
            options: [{ name: 'Srigar', id: 1 }, { name: 'Sam', id: 2 }]
        };
    }

    onSelect(selectedList, selectedItem) {
        console.log(selectedItem)
        console.log(selectedList)
    }

    onRemove(selectedList, removedItem) {
        console.log(selectedList)
        console.log(removedItem)
    }
    render() {
        return (<div>
            <Multiselect
                options={this.state.options}
                selectedValues={this.state.selectedValue}
                onSelect={this.onSelect}
                onRemove={this.onRemove}
            />
        </div>)
    }
}

标签: reactjsnpmstenciljs

解决方案


虽然我不推荐它,但可以在 Stencil 中使用 react 组件,方法是在组件中包含 react 运行时(是的,听起来很无效)。

在这里查看我的答案:https ://stackoverflow.com/a/62046928/2897426 。它用于使用react-bootstrap非常相似的组件。请注意,Stencil 的 JSX(或真正的 TSX)与 React 的 JSX 不兼容,因此您不能使用 JSX 来传递属性。会是这样的

import { Component, h, State } from '@stencil/core';
import { Multiselect } from 'multiselect-react-dropdown';
import ReactDOM from 'react-dom';
import React from 'react';

@Component({
    tag: 'ui-card',
    styleUrl: 'style.scss',
    shadow: true
})
export class UiCard {
  @Element() host: HTMLUiCardElement;

  @State() state: any;

  @Watch('state')
  onStateChange() {
    const props = {
      options: this.state.options,
      // ...
    };

    ReactDOM.render(React.createElement(Multiselect, props), this.host);
  }

  componentWillLoad() {
    this.onStateChange();
  }

  render() {
    return <Host />;
  }
}

同样,我不建议这样做,它会在整个反应运行时完全膨胀你的组件。只能说有可能。


推荐阅读