从Pug传递参数到JSX

3

我正在使用Express和React构建一款游戏。我需要在我的index.jsx文件中访问userId来执行控制器上的操作,比如增加用户分数。

我的路由渲染一个index.pug文件,并传递一个user_id参数:

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

然后我可以在pug文件中访问userId,像这样:
// index.pug
body
  div#errors
  #root
  p #{userId} // prints the User Id

现在我需要在包含React组件的index.jsx文件中访问这个userId参数。
class Cell extends React.Component {
  render() {
      return (
        <button onClick={() => this.props.onClick()}>
          {userId}
        </button>
      )
    } 
  }    

但是那样做并不起作用,正如我所预料的那样。有什么想法吗?
1个回答

0

你可以使用 window 对象来实现。

假设在你的 .pug 文件中:

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

现在你可以在 react 组件中通过 window.userId 访问 userId
class Cell extends React.Component {
  render() {
      return (
        <button onClick={() => this.props.onClick()}>
          {window.userId}
        </button>
      )
    } 
  } 

我使用 window 对象以相同的方式将 pug 数据传递给 react 组件。 - Jyothi Babu Araja
谢谢!确实是这样子。这是我实现它的方式: script. window.fbId = !{JSON.stringify(userId)};然后在 index.jsx 中: , document.getElementById('root') )``` - Antonin Archer
哦,你传递给 render 函数了。那也没问题。 - Jyothi Babu Araja

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接