簡體   English   中英

反應自定義組件未呈現

[英]React Custom component not getting rendered

*自定義組件未在 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"));

您需要像這樣將道具傳遞給組件:

const helloElement = <CComponent classname='xyz' content='helloWorld' />

您將值作為孩子傳遞,將值作為道具傳遞,您可以這樣做:
<CComponent classname='xyz' content='helloWorld' />

根據反應文檔:

React.createElement(
   type,
   [props],
   [...children]
)

<CComponent>{{ classname: "xyz", content: "helloWorld" }}</CComponent>這由 babel 編譯為:

var helloElement = React.createElement(CComponent, null, {
  classname: 'xyz',
  content: 'helloWorld'
})

但是<CComponent classname='xyz' content='helloWorld' />

編譯為

var helloElement= React.createElement(CComponent, {
  classname: "xyz",
  content: "helloWorld"
})  

因此在 UI 上呈現

使用 babel 7 和 react >= 16 它不會工作。 CComponent 使用 {classname,content} object 獲取 children 道具。

您可以嘗試稍微更改語法,它將完美呈現

<CComponent {...{ className: "xyz", content: "helloWorld" }} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM