无法在REACT中的类中使用常量 [英] Unable to use const within a class in React

查看:27
本文介绍了无法在REACT中的类中使用常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习本教程

https://nickymeuleman.netlify.com/blog/gatsby-pagination#navigate-to-previousnext-page

一切正常,但我无法在类中添加const。我正在使用VSC来编写网站代码,它似乎就是不喜欢。

这是我试图将Const放在其中的类。因为我是新手,所以在不使用插件的情况下找到解决方案时,我有点迷茫。

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>
  }

您可以做的是不使用常量将变量声明为类字段:

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>
  }

这篇关于无法在REACT中的类中使用常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆