将参数从哈巴狗传递给JSX [英] Pass a param from pug to JSX

查看:172
本文介绍了将参数从哈巴狗传递给JSX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express和React构建游戏.我需要访问index.jsx文件中的userId才能在控制器上执行操作,例如增加用户得分.

I'm building a game using Express and React. I need to access the userId in my index.jsx file to perform actions on my controllers, like increment the user score.

我的路线在传递user_id参数时呈现了index.pug文件:

My route renders an index.pug file while passing a user_id param:

//server.js
app.get('/', function (req, res) {
  const userId = req.query.userId
  res.render('index', {userId: userId})
})

然后我可以在我的pug文件中访问userId,如下所示:

Then I can access the userId in my pug file, like this:

// index.pug
body
  div#errors
  #root
  p #{userId} // prints the User Id

现在,我需要在包含React Components的index.jsx文件中访问此userId参数.

Now I need to access this userId param in my index.jsx file that contains the React Components.

class Cell extends React.Component {
  render() {
      return (
        <button onClick={() => this.props.onClick()}>
          {userId}
        </button>
      )
    } 
  }    

但是,这不起作用,正如我预期的那样.有什么想法吗?

But that doesn't work, as I expected. Any ideas?

推荐答案

您可以使用window对象

在您的.pug文件中说

script.
   var userId = '#{userId}'; //assigning pug value to window object.

现在您可以将react组件中的userId作为window.userId

Now you can access userId in react component as window.userId

class Cell extends React.Component {
  render() {
      return (
        <button onClick={() => this.props.onClick()}>
          {window.userId}
        </button>
      )
    } 
  } 

这篇关于将参数从哈巴狗传递给JSX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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