繁体   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