【问题标题】:Pass a param from pug to JSX将参数从 pug 传递到 JSX
【发布时间】:2017-01-02 01:14:35
【问题描述】:

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

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

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

但这不起作用,正如我所料。有什么想法吗?

【问题讨论】:

    标签: node.js reactjs express pug react-jsx


    【解决方案1】:

    你可以使用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 组件
    • 谢谢!确实是这样。以下是我的实现方式:index.pug script. window.fbId = !{JSON.stringify(userId)}; 然后在 index.jsx 中:ReactDOM.render( &lt;Game userId={userId} /&gt;, document.getElementById('root') )
    • 哦,你传递给了render 函数。这也很好。
    猜你喜欢
    • 1970-01-01
    • 2018-02-06
    • 2018-07-02
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多