簡體   English   中英

ReactJS - {this.props.children} 未定義

[英]ReactJS - {this.props.children} is undefined

我看過很多與這個論點相關的帖子,但我無法理解為什么{this.props.children}在我的應用程序中未定義(我真的是 ReactJS 的新手)

App.js開始,這是我的主要組件,我有這個:

import React, {Component} from 'react';
import Dashboard from './layouts/Dashboard';

class App extends Component {
    render() {
        return(
            <div id="container">
                <Dashboard />
            </div>
        );
    }
}

因此, Dashboard.js必須編寫代碼以呈現頂部欄和左側欄,“動態”內容將位於中心(這是我放置{this.props.children}

Dashboard.js

render() {
    return(
        <div className="content" id="wrapper">
            <!-- Navbar and sidebar code -->
            <-- this is the dynamic content -->
            <div id="page-wrapper" className="page-wrapper" ref="pageWrapper">
                {this.props.children}
            </div>
        </div>
    );
}

現在的路由器非常簡單:

<Route component={App}>
    <Route path='/' component={Home} />
</Route>

我省略了與 Home.js 相關的代碼,但這是一個簡單的div ,以 statyc 方式打印"Hello World"

儀表板組件已呈現,但在我擁有 {this.props.children} 的部分中沒有放置“Hello World”

您無法通過 this.props.children 訪問組件的子組件。 this.props.children 指定由所有者傳遞給您的孩子:

var App = React.createClass({
  componentDidMount: function() {
    // This doesn't refer to the `span`s! It refers to the children between
    // last line's `<App></App>`, which are undefined.
    console.log(this.props.children);
  },

  render: function() {
    return <div><span/><span/></div>;
  }
});

ReactDOM.render(<App></App>, mountNode);

要訪問您自己的子組件(跨度),請在其上放置 refs https://facebook.github.io/react/docs/more-about-refs.html

您必須將孩子傳遞給儀表板:

class App extends Component {
    render() {
        return(
            <div id="container">
                <Dashboard>{this.props.children}</Dashboard>
            </div>
        );
    }
}

Dashboard沒有子項。

在 App.js 中將<Dashboard />更改為<Dashboard>{this.props.children}</Dashboard>以便您的 Dashboard 組件可以訪問您通過Route傳遞的組件。

您可以檢查 Dashboard.js 中是否存在子項

render() {
  return <div>{this.props.children !== undefined && this.props.children}</div>
}

暫無
暫無

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

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