[英]React Custom component not getting rendered
* Custom component is not getting render on UI , also note that I have element by id: root *自定义组件未在 UI 上呈现,还请注意,我有 id 元素:root
function CComponent(prop) {
const element = (
<div className="container">
<div className={prop.classname}>{prop.content}</div>
</div>
);
return element;
}
const helloElement = (
<CComponent>{{ classname: "xyz", content: "helloWorld" }}</CComponent>
);
console.log(helloElement);
ReactDOM.render(helloElement, document.getElementById("root"));
You need to pass props to component like this:您需要像这样将道具传递给组件:
const helloElement = <CComponent classname='xyz' content='helloWorld' />
You are passing your values as children, to pass values as props, you do this:您将值作为孩子传递,将值作为道具传递,您可以这样做:
<CComponent classname='xyz' content='helloWorld' />
According to react doc:根据反应文档:
React.createElement(
type,
[props],
[...children]
)
<CComponent>{{ classname: "xyz", content: "helloWorld" }}</CComponent>
this was compiled by babel to: <CComponent>{{ classname: "xyz", content: "helloWorld" }}</CComponent>
这由 babel 编译为:
var helloElement = React.createElement(CComponent, null, {
classname: 'xyz',
content: 'helloWorld'
})
But <CComponent classname='xyz' content='helloWorld' />
但是<CComponent classname='xyz' content='helloWorld' />
got compiled to编译为
var helloElement= React.createElement(CComponent, {
classname: "xyz",
content: "helloWorld"
})
Hence was rendered on UI因此在 UI 上呈现
With babel 7 and react >= 16 it wont work.使用 babel 7 和 react >= 16 它不会工作。 CComponent gets a children prop with {classname,content} object. CComponent 使用 {classname,content} object 获取 children 道具。
You can try change the syntax a bit and it will render perfectly to您可以尝试稍微更改语法,它将完美呈现
<CComponent {...{ className: "xyz", content: "helloWorld" }} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.