如何在JSX中的HTML中使用局部变量?

时间:2019-10-09 12:04:05

标签: reactjs jsx gatsby

如何在下面的Gatsby代码中使用meta=data.site.siteMetadata之类的本地变量? Var / Const / $似乎无效。我想使用此meta var而不是data

import React from "react"
import { graphql } from "gatsby"

export default ({ data }) => (
  <div>
    <h1>About {data.site.siteMetadata.title}</h1>
    <p>We're a very cool website you should return to often.</p>
  </div>
)

export const query = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
  }
`

如何进行以下工作:

import React from "react"
import { graphql } from "gatsby"

export default ({ data }) => (
  <div>
    {var meta=data.site.siteMetadata}
    <h1>About {meta.title}</h1>
    <p>We're a very cool website you should return to often.</p>
  </div>
)

export const query = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
  }
`

2 个答案:

答案 0 :(得分:3)

我认为问题是关于React而非特定于Gatsby

关于如何在功能组件中使用局部变量的简单示例:

const MyComponent = ({ data }) => {
  const myLocalVariable = data.site.siteMetadata.title;
  return (
    <div>
      <h1>About {myLocalVariable}</h1>
      <p>We're a very cool website you should return to often.</p>
    </div>
  );
};

export default MyComponent;

有关更多详细信息,您的graphql查询将返回下一个对象:

{
  "data": {
    "site": {
      "siteMetadata": {
        "title": "My Site Title"
      }
    }
  }
}

因此,您可以执行以下操作:

import React from 'react';
import { graphql } from 'gatsby';

export default ({ data }) => {
  // meta is an object.
  const meta = data.site.siteMetadata;
  return (
    <div>
      <h1>About {meta.title}</h1>
      <p>We're a very cool website you should return to often.</p>
    </div>
  );
};

export const query = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
  }
`;

您应该阅读react文档中的Getting Started部分, Gatsby 是React的站点生成器,因此事先了解所有React概念非常重要。

答案 1 :(得分:1)

您做对了。但是,只需替换return方法。

old:

   export default ({ data }) => (
      <div>
        {var meta=data.site.siteMetadata}
        <h1>About {meta.title}</h1>
        <p>We're a very cool website you should return to often.</p>
      </div>
    )

新:

   export default ({ data }) => {
    var meta= data.site.siteMetadata;
    return (
     <div>
        <h1>About {meta.title}</h1>
        <p>We're a very cool website you should return to often.</p>
      </div>
     )
    }

=> () //函数中的语法仅返回您在其中编写的内容。

只需将其替换为

=> { 
// Here you can define the variables
return ()
}