我正在使用 SurveyJs 创建调查。在这样做时,我希望创建一个按钮来添加到每个问题的标题中。我已经能够用 Javascript 做以下事情,但我希望用 React 做同样的事情。
呈现调查效果很好,所以我认为不值得展示。以下是每个问题都被渲染时的回调函数。以下工作正常:
const onAfterRenderQuestion = (survey, options) = {
// create the button
const btn = document.createElement("button")
btn.innerHTML = "Click me!"
// define what the button should do
btn.onClick = function () {
// do whatever
}
// get the question title from the survey and append the button to the end of it
let header = options.htmlElement.querySelector("h5")
if (!header) header = options.htmlElement
header.appendChild(btn)
}
上面的代码工作正常,如您所见,它使用的是 Javascript。但是,我正在尝试使用 React 做同样的事情,但我做不到。现在,我有这个:
// create the button component
const myButtonElement = (
<Button onClick={() => {*call some function*}}
)
let header = options.htmlElement.querySelector("h5")
if (!header) header = options.htmlElement
// create the entire component
const questionTitle = React.createElement("div", {}, header)
const buttonElement = React.createElement("div", {}, myButtonElement)
const titleWithButton = React.createElement("div", {}, [questionTitle, buttonElement])
ReactDOM.render(titleWithButton, document.getElementById(options.question.id))
但是,上面的代码会导致以下错误:
错误:对象作为 React 子项无效(找到:[object HTMLHeadingElement])。如果您打算渲染一组子项,请改用数组。
即使不熟悉 Surveyjs,我如何才能使用 React 将元素简单地附加到现有元素,类似于我已经使用 Javascript 完成的方式?