在功能组件中实现 tagbox 小部件

问题描述

我一直致力于使用功能组件在 reactjs 中创建surveyjs 表单。其他一切都非常适合,但问题在于restfull tagBox 小部件。

一个很好的例子可以在类组件 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;

因此,您将获得类中仅剩的 render 函数。

这是你的分叉 plunker - 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",choicesByUrl: {
          url: "https://restcountries.eu/rest/v2/all"
        },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

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