将变量从玉器文件传递到React组件 [英] Passing a variable from a jade file to a React Component
问题描述
我无法将变量从.jade文件传递到react组件. 这是我的翡翠文件的一部分:
I am having trouble passing a variable from a .jade file to a react component. Here is a section of my jade file:
block content
#example
var user = '#{user}';
span #{user.id}
span #{user.displayName}
block content
#example
var user = '#{user}';
span #{user.id}
span #{user.displayName}
这是app.jsx,我想访问变量用户的react组件.
And here is app.jsx, the react component that I would like to have access to the variable user.
var React = require('react');
var HelloWorld = require('./HelloWorld.jsx');
var $ = jQuery = require('../../libraries/jquery/dist/jquery');
var bootstrap = require('../../libraries/bootstrap-sass-official/assets/javascripts/bootstrap');
React.render(
<HelloWorld/>,
document.getElementById('example')
);
我尝试从app.jsx将this.props.user
和window.user
记录到控制台,但未定义.理想情况下,我希望app.jsx中的this.props.user
是jade文件有权访问的用户.然后,我将能够将该用户变量传递到HelloWorld组件中.也许有更好的方法可以做到这一点,而我刚接触玉石和做出反应,我一定会喜欢这个建议.
I've tried logging this.props.user
and window.user
to the console from app.jsx but it is undefined. Ideally, I would like this.props.user
in app.jsx to be the user that the jade file has access to. Then I would be able to pass that user variable into the HelloWorld component, for example. Perhaps there's a better way of doing this and I, being new to jade and react, would certainly appreciate that advice.
推荐答案
您可以在呈现之前手动提取DOM属性,例如:
You can extract the DOM attributes manually before rendering, something like:
var node = document.getElementById('example')
var user = {
id: node.children[0].textContent,
displayName: node.children[1].textContent
}
React.render(<HelloWorld user={user} />, node)
但是我可能建议您使用JSON或ajax来获取数据,而不是解析DOM.
But I would probably suggest you use JSON or ajax to fetch the data instead of parsing the DOM.
这篇关于将变量从玉器文件传递到React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!