将参数从哈巴狗传递给JSX [英] Pass a param from pug to 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屋!