簡體   English   中英

使用 React 渲染 props.children

[英]Rendering props.children with React

有人可以解釋為什么我必須將“props.children”包裹在“div”中才能使 react-router 工作。

這有效:

export default (props) => {
        return (
            <div id="main-template">
                {props.children}
            </div>
        );
}

但是,這不會:

export default (props) => {
        return (
                {props.children}
        );
}

任何解釋將不勝感激。

如果您有一個子節點,則不需要將props.children包裝到{} ,您只需返回props.children

const Component = (props) => {
    return props.children;
};

Example

例如,如果您有多個節點

<p>1</p>
<p>2</p>
<p>3</p>

必須children元素包裝到一個根元素,因為組件必須只返回一個根元素,你不能返回多個,像這樣

return (
  <p>1</p>
  <p>2</p>
  <p>3</p>
)

JSX 將看起來像 HTML 的代碼轉換為 javascript 函數調用。 返回多個頂級組件

return (
    <p>text</p>
    <p>text</p>
    <p>text</p>
);

變成了

return (
    React.createElement('p', null, 'text'),
    React.createElement('p', null, 'text'),
    React.createElement('p', null, 'text')
);

這是無效的。 由於您需要返回單個值,因此不能呈現多個頂級元素。 React 團隊一直在想辦法解決這個問題,但目前還沒有解決方案。

您不需要將props.children包裹在 div 中。 這里的問題是您錯誤地使用了return語句中的括號。 每當我們有一個多行 jsx 塊時,就會完成左括號和右括號。

在您的情況下,您沒有多行 jsx,實際上您的是單行 javascript 表達式,因此您可以這樣做:

export default (props) => {
        return props.children;
}

為什么不用花括號? 因為那里沒有任何 jsx。 花括號僅用於將 JavaScript 變量注入 jsx 時。

有人可以解釋為什么我必須將“props.children”包裹在“div”中才能使 react-router 工作。

這不是 React Router 或props.children問題。 React 需要由父元素包裝的元素集合(“子元素”)。

有幾種解決方案:

https://reactjs.org/docs/fragments.html

<Fragment>{props.children}</Fragment>
<>{props.children}</>
<div>{props.children}</div>

暫無
暫無

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

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