将参数从 pug 传递给 JSX
Pass a param from pug to JSX
我正在使用 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>
)
}
}
但正如我所料,这不起作用。有什么想法吗?
您可以使用 window
对象
假设在您的 .pug
文件中
script.
var userId = '#{userId}'; //assigning pug value to window object.
现在您可以在 react
组件中访问 userId
作为 window.userId
class Cell extends React.Component {
render() {
return (
<button onClick={() => this.props.onClick()}>
{window.userId}
</button>
)
}
}
我正在使用 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>
)
}
}
但正如我所料,这不起作用。有什么想法吗?
您可以使用 window
对象
假设在您的 .pug
文件中
script.
var userId = '#{userId}'; //assigning pug value to window object.
现在您可以在 react
组件中访问 userId
作为 window.userId
class Cell extends React.Component {
render() {
return (
<button onClick={() => this.props.onClick()}>
{window.userId}
</button>
)
}
}