无法读取未定义反应的 属性 道具

cannot read property props of undefined react

目前正在学习 React 'props'。在组件内渲染道具时,传递 'name' 和 'age':

时出现编译错误

"Cannot read property 'name' of undefined."

这是我的代码:

仪表板

import React, { Component } from 'react';
import SummaryWidget from '../../Components/SummaryWidgets/SummaryWidget';

class Dashboard extends Component {
  constructor(props) {
    super(props);
  }

  render() {

    return (
      <div className="animated fadeIn">
        <Row>
          <Col xs="12" sm="6" lg="6">

            <SummaryWidget name='David' age='20'/>


          </Col>

          <Col xs="12" sm="6" lg="6">


          </Col>

        </Row>

      </div>
    )
  }
}
export default Dashboard;

摘要小部件

import React, { Component } from 'react';

class SummaryWidget extends Component {

  constructor(props) {
    super(props);
  }

  render (props) {
    return (
      <div className="SummaryWidget">
      <span>{props.name}{props.age}</span>
      </div>
    )
  }

}

export default SummaryWidget;

请将渲染方法更改为

render () {
    return (
      <div className="SummaryWidget">
      <span>{this.props.name}{this.props.age}</span>
      </div>
    )
  }

顺便说一句:如果您不想在构造函数中做任何事情,则不必实现它。此外,如果您不需要状态和任何生命周期方法,您应该将您的组件作为无状态组件。喜欢:

import React from 'react';

const SummaryWidget = ({ name, age }) => (
  <div className="SummaryWidget">
    <span>{name}{age}</span>
  </div>
);

export default SummaryWidget;

更改您的 SummayWidget 组件
class SummaryWidget extends Component {

  constructor(props) {
    super(props);
  }

  render (props) {
    return (
      <div className="SummaryWidget">
      <span>{props.name}{props.age}</span>
      </div>
    )
  }

}

class SummaryWidget extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div className="SummaryWidget">
      <span>{this.props.name}{this.props.age}</span>
      </div>
    )
  }

}

您不需要像这样在 class 组件中添加 render (props)

如果您需要 class 组件,请按上述操作,或者如果您需要功能组件,请按@kevin 建议的方式操作。

working demo