[英]Can I compose a component without JSX in React?
I'm trying to figure out if it's possible to compose a React component without the use of JSX?我试图弄清楚是否可以在不使用 JSX 的情况下编写 React 组件? I'm expecting the header element to render with the nested h1 and h2.
我期待 header 元素使用嵌套的 h1 和 h2 进行渲染。 However, what is actually showing is just the paragraph tag.
但是,实际显示的只是段落标签。 Why is that React element the only one rendering?
为什么那个 React 元素是唯一的一个渲染?
This Codepen example on the React website was used as a reference to mimic the compiled JavaScript, but like I said I'm not getting the same outcome when just using React.createElement()
. React 网站上的这个 Codepen 示例被用作模仿编译后的 JavaScript 的参考,但就像我说的那样,仅使用
React.createElement()
时我没有得到相同的结果。 https://codepen.io/pen?editors=0010 https://codepen.io/pen?editors=0010
var Header = createReactClass({
render: function() {
return React.createElement(
"header", null, React.createElement(
"h1", {"className": "main"}, this.props.title
), React.createElement(
"h2", {"className": "submain"}, this.props.subtitle
)
)
}
});
function App() {
return (
React.createElement(Header, {"title": "A", "subtitle": "B"}),
React.createElement("p", null, "Lorem Ipsum")
);
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
You needed another surrounding element in your App component.您的 App 组件中需要另一个周围元素。 Otherwise it will only show paragraph, the last instance of
React.createElement
.否则它只会显示段落,即
React.createElement
的最后一个实例。
function App() {
return React.createElement(
"div",
null,
React.createElement(Header, { title: "A", subtitle: "B" }),
React.createElement("p", null, "Lorem Ipsum")
);
}
Unless you have a specific reason for not using JSX, I (and in fact the React docs) would recommend against it.除非您有不使用 JSX 的特定原因,否则我(实际上是 React 文档)会建议不要使用它。
You can make your life a whole lot easier by just using JSX.只需使用 JSX,您就可以让您的生活变得更轻松。
eg例如
const Header = (props) => {
const { subtitle, title } = props;
return (
<>
<h1 className="main"> {title} </h1>
<h2 className="submain"> {subtitle} </h2>
</>
);
}
function App() {
return (
<React.Fragment>
<Header title="hello" subtitle="world" />
<p>Lorem Ipsum</p>
</React.Fragment>
);
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.