reactjs - 无法在 React 的类中使用 const
问题描述
我正在关注本教程
https://nickymeuleman.netlify.com/blog/gatsby-pagination#navigate-to-previousnext-page
一切正常,但我无法在类中添加 const 。我正在使用 VSC 对网站进行编码,但它似乎并不喜欢它。
这是我试图在其中放置 const 的类。由于我是 React 新手,因此在不使用插件的情况下寻找解决方案时有些迷失。
export default class PostList extends React.Component {
render() {
const posts = this.props.data.allMarkdownRemark.edges
return (
<Layout>
<Head title="Posts" />
<div className={layoutStyles.pageHeader}>
<h2>Posts</h2>
<span>Just my ramberlings</span>
</div>
{posts.map(({ node }) => {
const title = node.frontmatter.title || node.fields.slug
return (
<div className={postPageStyles.postItem}>
<div className={postPageStyles.postItemTitle}>
<h2>{title}</h2>
<span>Posted on {node.frontmatter.date}</span>
</div>
<div>
<p>{node.excerpt}</p>
<Link to={`${node.fields.slug}`}>
<span>Continue Reading</span>
<span role="img"> </span>
</Link>
</div>
</div>
)
})}
</Layout>
)
}
}
解决方案
您确实不能const
在“就像那样”的类中使用:
class App extends React.Component {
const a = 2 // will throw a syntax error
render(){
return <div>Hello World</div>
}
您可以做的是不使用 const 将变量声明为类字段:
class App extends React.Component {
a = "john";
render(){
//now you can access a via `this`
return <div>{`Hello ${this.a}`}</div>
}
或者,如果您不需要它以某种方式“绑定”到您的组件,您可以在类之外声明它。
const a = "john"
class App extends React.Component {
render(){
//you can simply access `a`
return <div>{`Hello ${a}`}</div>
}
推荐阅读
- angular - 带有异步选项的 mat-selection-list 重置选项更改时的反应控制值
- javascript - 如何将 Chromium 中地址栏和选项卡的外观更改为与所附图像相似
- python - 带有三元运算符的海象运算符的正确语法是什么?
- python-3.x - 如何在一个“尝试”块中引发同一错误的多个异常
- powershell - 通过 power shell 脚本从 Outlook 中删除基于主题的邮件
- javascript - React 本机状态未使用 animated.start() 中的钩子更新
- hyperledger-fabric - 在超级账本结构中使用 Solidity 智能合约
- sql - 如何从另一个表插入更新数据?
- java - Spring MVC:通过 REST 端点将字符串日期转换为日期
- android - 未解决参考