[英]How do I render a string as children in a React component?
拿一個簡單的組件:
function MyComponent({ children }) {
return children;
}
這有效:
ReactDOM.render(<MyComponent><span>Hello</span></MyComponent>, document.getElementById('stage'));
但這沒有(我刪除了<span/>
):
ReactDOM.render(<MyComponent>Hello</MyComponent>, document.getElementById('stage'));
因為React嘗試在字符串上調用render
:
Uncaught TypeError: inst.render is not a function
另一方面,這很好用:
ReactDOM.render(<p>Hello</p>, document.getElementById('stage'));
如何使<MyComponent/>
表現得像<p/>
?
如果您使用的是React 16.2或更高版本,則可以使用React片段執行此操作:
const MyComponent = ({children}) => <>{children}</>
如果您的編輯器不支持片段語法,這也將起作用:
const MyComponent = ({children}) =>
<React.Fragment>{children}</React.Fragment>
請記住,就React而言,您仍在創建和返回組件(MyComponent類型) - 它只是不創建額外的DOM標記。 這是一個混合包:
好處:你仍會在React Debug Tools中看到<MyComponent>
標簽。
缺點:如果您正在使用Typescript或Flow,您的轉換器可能會抱怨,因為MyComponent的返回類型仍然是React元素(React.ReactElement)。
差別是<p>
是一個html元素而MyComponent
是一個React Component。
反應的組分需要渲染/ 返回一個單個部件或一個單一的HTML元素。
'Hello'
既不是。
您至少需要一個頂級HTML元素。 您的組件實際上不能只輸出字符串,這不是React的工作方式。
最簡單的解決方案是簡單地讓MyComponent
在span或div中包裝它的輸出。
function MyComponent({ children }) {
return <span>{ children }</span>;
}
目前,在組件的渲染中,您只能返回一個節點; 如果你有一個要返回的div列表,你必須將你的組件包裝在div,span或任何其他組件中。
你要返回的不是根節點。 您正在返回一個react組件,它返回一個字符串,它應該返回一個HTML元素。
您可以傳遞已經用HTML元素包裝的字符串(就像您在示例中所做的那樣),也可以將字符串包裝在“MyComponent”中的HTML元素中,就像這樣
function MyComponent({ children }) {
return <span>{ children }</span>;
}
React可以呈現React組件(類)或HTML標簽(字符串)。 任何HTML標記按慣例都是小寫的,其中Component是大寫的。 每個React組件都必須只呈現一個Tag(或null)。 回答你的問題:你做不到。
在上面的示例中,您將呈現使用children
屬性給出的內容,其中這將在內部呈現標記或無效的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.