1

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

有一个很好的例子可以在类组件https://codesandbox.io/s/ljnh1中使用它,但是我很难将它转换为功能组件。

您的任何帮助都会非常感谢

4

1 回答 1

0

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

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",
        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

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

于 2021-05-13T11:18:24.120 回答