【问题标题】:Root component as React.component根组件作为 React.component
【发布时间】:2016-12-28 09:39:50
【问题描述】:

我正在使用react-boilerplate,并且我正在尝试将App component 更改为扩展React.Component,因为我正在尝试通过遵循this example 来实现身份验证并根据身份验证状态显示/显示侧边菜单.可以看到,原本 props 是通过 props 参数传递给 App 的。我已将 App/index.js 类更改为:

import React from 'react';
import Header from 'components/Header';
import SideMenu from 'containers/SideMenu';
import Footer from 'components/Footer';
import auth from 'utils/auth'

export class App extends React.Component {
  render() {
  console.log(props)
  return (
      <div>
        <Header />
        <SideMenu />
        {React.Children.toArray(props.children)}
        <Footer />
      </div>
    );
  }
}

App.propTypes = {
  children: React.PropTypes.node,
};

export default App;

这会抛出 props 未定义的错误:

ReferenceError: props 未定义 应用程序渲染 **/App/index.js

可以看到根路由是如何实例化的here:

// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript node.js reactjs react-boilerplate


    【解决方案1】:

    使用:

    this.props.children
    

    您也不需要将孩子更改为数组

    只需使用:

     {this.props.children}
    

    【讨论】:

    • 非常感谢,这行得通。虽然有点困惑,所以如果我调用 this.props 它是类的参数,如果我只使用道具,它是全局范围内的对象?它不也查找类变量吗?
    • 如果你想使用一个类变量,它总是通过'this'。在不使用“this”的情况下使用将始终查找全局变量或您在方法内部定义的内容,而不是在类本身上。在 React 中,props 和 state 都在类本身上,你总是需要通过 this.state/this.props 访问它
    • 谢谢 :) 这解释了事情
    猜你喜欢
    • 2021-04-25
    • 2017-01-30
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2018-05-29
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多