在功能组件中实现标签框小部件

implementing tagbox widget in functional components

我一直致力于使用函数式 components.Everything 在 reactjs 中创建 surveyjs 表单,否则非常适合,但问题是关于 restfull tagBox 小部件。

在 class 组件 https://codesandbox.io/s/ljnh1 中有一个很好的例子,但我很难将它转换成功能组件。

你的任何帮助都会很棒 谢谢

您可以将所有静态初始化移到组件外部:

import React, { Component } from "react";
import $ from "jquery";
import select2Init from "select2";
import "select2/dist/css/select2.min.css";

import * as Survey from "survey-react";
import * as widgets from "surveyjs-widgets";

import "survey-react/modern.css";
import "./index.css";

Survey.StylesManager.applyTheme("modern");

window["$"] = window["jQuery"] = $;
select2Init();
widgets.select2(Survey);
widgets.select2tagbox(Survey);

class SurveyComponent extends Component {
  render() {
    const json = {
      elements: [
        {
          type: "tagbox",
          isRequired: true,
          choicesByUrl: {
            url: "https://restcountries.eu/rest/v2/all"
          },
          name: "countries",
          title:
            "Please select all countries you have been for the last 3 years."
        }
      ]
    };
    const survey = new Survey.Model(json);

    return <Survey.Survey model={survey} />;
  }
}

export default SurveyComponent;

因此您将获得 class 中唯一的 render 函数。

这是你的分叉插件 - https://codesandbox.io/s/new-brook-wsmot?file=/src/SurveyComponent.jsx

更新 1

功能组件

import React, { Component } from "react";
import $ from "jquery";
import select2Init from "select2";
import "select2/dist/css/select2.min.css";

import * as Survey from "survey-react";
import * as widgets from "surveyjs-widgets";

import "survey-react/modern.css";
import "./index.css";

Survey.StylesManager.applyTheme("modern");

window["$"] = window["jQuery"] = $;
select2Init();
widgets.select2(Survey);
widgets.select2tagbox(Survey);

function render() {
  const json = {
    elements: [
      {
        type: "tagbox",
        isRequired: true,
        choicesByUrl: {
          url: "https://restcountries.eu/rest/v2/all"
        },
        name: "countries",
        title: "Please select all countries you have been for the last 3 years."
      }
    ]
  };
  const survey = new Survey.Model(json);

  return <Survey.Survey model={survey} />;
}

export default render;

这是更新后的代码沙箱 - https://codesandbox.io/s/crazy-elgamal-01nku?file=/src/SurveyComponent.jsx

当然 - 调查模型应该作为道具值传递