gpt4 book ai didi

javascript - 如何将生成的 HTML 传递给 JSX 中的渲染函数?

转载 作者:行者123 更新时间:2023-12-01 02:52:42 27 4
gpt4 key购买 nike

在 JSX 组件的渲染函数中传递生成的 HTML 是合法的方法吗?

...
//get variables elsewhere
const input = <input type={inputType} ... />

return (
{input}
)
...

当我尝试将其构建为字符串时,例如const input = '<input type="' + inputType'" + />'它被呈现为纯文本。

<小时/>

其实,我的return是:

return (
<div>{input}</div>
)

最佳答案

除了 return 之外,您发布的代码完全没问题。 (我们稍后会讨论这个问题);您不需要或不想使用字符串。

请记住,JSX 只是 JavaScript 代码的语法糖:

const input = <input type={inputType} />;

...只是 React.createElement 的加糖版本:

const input = React.createElement("input", { type: inputType });

它创建元素对象,您当然可以在函数之间传递该对象,并且可以通过从 render 返回它来渲染该对象。 .

要实现此返回,您只需:

return input;

您的return ({input})不起作用,因为您尝试使用 JSX 语法在 JSX 之外插入 JavaScript 表达式 ( {...} ) 外部

实例:

class Example extends React.Component {
getTheThing() {
const inputType = "text";
const input = <input type={inputType} />;
return input;
}
render() {
const input = this.getTheThing();
return input;
}
}

ReactDOM.render(
<Example />,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<小时/>

重新编辑:

Actually, my return is:

return (
<div>{input}</div>
)

没关系(除了缺少的 ; — 我不喜欢依赖 ASI),因为您正在使用 {...}在 JSX block 中 ( <div>...</div> )。

实例:

class Example extends React.Component {
getTheThing() {
const inputType = "text";
const input = <input type={inputType} />;
return input;
}
render() {
const input = this.getTheThing();
return (
<div>{input}</div>
);
}
}

ReactDOM.render(
<Example />,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

关于javascript - 如何将生成的 HTML 传递给 JSX 中的渲染函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46872890/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com