javascript - React 17 - 无法读取未定义的属性“道具”
问题描述
在我见过this.props
的教程中,用于获取道具和使用它们。当我写这个并传递数据是好的,但是为了得到它们它告诉我这个:
无法读取未定义的属性'props'
有什么问题?我怎样才能访问它们?
import '../styles/Navbar.css';
function Navbar() {
return (
<h2>{this.props.name} God is dead!</h2>
);
}
export default Navbar;
解决方案
您的功能组件不使用 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>;
推荐阅读
- wpf - 调用 WCF 服务时参数的函数转换不成功
- python - 如何从现有脚本中使用 tkinter 调用函数
- ruby-on-rails - Rails 从数组中删除子数组
- java - FirebaseNetworkException 无法转换为 com.google.firebase.auth.FirebaseAuthException
- html - 为什么向我的 div 添加边距会将其内容(列)推离页面?
- random - 如何提前创建一个公开可见的、可证明的随机种子?(可验证的随机数)
- python - 这段 Python 代码有什么作用?括号的解释
- python - 在 Python 中求解线性方程组 AX = B,np.linalg.solve 不起作用
- java - 基于前辈的平均项目完成时间
- wpf - 单击时在用户控件中更改按钮内容