Passing a variable from a jade file to a React Component

时光怂恿深爱的人放手 提交于 2019-12-12 12:26:55

问题


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}

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')
);

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.


回答1:


I haven't used React, I'm not sure what React.render does or what its arguments are for so this might not be applicable.

To get a variable from server to client javascript try templating a json string into the html and loading it from the javascript. EJS handles quote escaping and I think Jade does too. For reference content!= safeString tells Jade to skip escaping, so does content !{safeString}.

- var user={id:1, displayName:'foo'}
#example
  meta(data-userJSON=JSON.stringify(user))
script(src="//code.jquery.com/jquery-1.11.3.min.js")
script.
  var user = JSON.parse(
    $('#example meta').attr('data-userJSON')
  )
  console.log(user);
span #{user.id}
span #{user.displayName}



回答2:


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)

But I would probably suggest you use JSON or ajax to fetch the data instead of parsing the DOM.




回答3:


Try this answer (I have tried to add a comment but it won't let me).

In your jade you will have:

script. var user = (!{JSON.stringify(user)});

Then, in React:

React.render( <HelloWorld user={user} />, document.getElementById('example') );

Be careful of passing data in the client you don't want anybody to see.




回答4:


Copying my answer from a similar question:

"There is a library that works well with express (and any other view rendering node framework) called react-helper (https://github.com/tswayne/react-helper). It pretty much handles everything you need to do to render react components in your view and pass data to them from the server in any node framework. You just make an entry point (js file) for webpack (the lib has a cli that can generate your webpack config for you) and add a line to your controller and view and your component will render on that page. Passing data into your react components is really simple:

const component = reactHelper.renderComponent('MyComponent', {user: 
req.session.user || ''})
res.render('view-to-render', {component})

There is also express middleware for react-helper (https://github.com/tswayne/express-react-helper) that allows you to add context that is available to all views, which is convenient for user session data.

app.use(function(req, res, next) {
 req.reactHelperContext.user = req.session.user || '';
});

Then, all of your react components will have the user prop without having to manually add that logic to every controller action."

The library will render your component for you and store it into a variable that you can pass to jade, then in jade you just print the variable like you would a string. That will handle the React.render for you, so you won't need that in your view anymore, or even the example div. Your entry point will just "register" the HelloWorld component and you're good to go.




回答5:


A simpler way of doing the accepted answer:

  1. Convert pug variable to json object

file.pug

script.
        var data = !{JSON.stringify(variable)}
  1. Include variable in component

file.jsx

class App extends React.Component {
    render() {
        return (
            <div>
                <h1>It works {data.name} </h1>
            </div>
        );
    }
}

ReactDOM.render(<App />, document.getElementById("react-target"));


来源:https://stackoverflow.com/questions/31397809/passing-a-variable-from-a-jade-file-to-a-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!