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

新手上路,请多包涵

我看过很多与这个论点相关的帖子,但我无法理解为什么 {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 以静态方式打印 "Hello World"

仪表板组件已呈现,但没有“Hello World”放置在我有 {this.props.children} 的部分

原文由 Mistre83 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 555
2 个回答

您必须将孩子传递给仪表板:

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

原文由 Dmitriy 发布,翻译遵循 CC BY-SA 3.0 许可协议

您不能通过 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

原文由 Kordi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题