首页 > 解决方案 > React 17 - 无法读取未定义的属性“道具”

问题描述

在我见过this.props的教程中,用于获取道具和使用它们。当我写这个并传递数据是好的,但是为了得到它们它告诉我这个: 无法读取未定义的属性'props'

有什么问题?我怎样才能访问它们?

import '../styles/Navbar.css';

function Navbar() {
    return (
        <h2>{this.props.name} God is dead!</h2>
    );
}

export default Navbar;

标签: javascriptreactjsreact-native

解决方案


您的功能组件不使用 props 对象。props作为参数添加到您的组件。它也只是props没有this IN组件,因为功能组件是无实例的,this未定义是导致错误的原因。

function Navbar(props) {
  return (
    <h2>{props.name} God is dead!</h2>
  );
}

对于函数式组件,在函数签名中解构命名的 props 也是很常见的。

function Navbar({ name }) {
  return (
    <h2>{name} God is dead!</h2>
  );
}

或作为箭头函数

const NavBar = ({ name }) => <h2>{name} God is dead!</h2>;

推荐阅读