首页 > 解决方案 > 无法在 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>
        )
    }
}

标签: reactjspaginationgatsby

解决方案


您确实不能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>
  }

推荐阅读