在JSX组件的render函数中传递生成的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 });
它创建了element对象,您当然可以在函数之间传递它,并且可以通过从
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>
重新编辑:
实际上,我的回报是:
return (
<div>{input}</div>
)
很好(除了缺少的
;
-我不在乎依赖ASI),因为您在JSX块({...}
)中使用<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>