Pass a param from pug to JSX

China☆狼群 提交于 2019-12-10 18:28:13

问题


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.

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

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

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

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?


回答1:


You can do using window object

Let's say in your .pug file

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

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


来源:https://stackoverflow.com/questions/41416236/pass-a-param-from-pug-to-jsx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!