Is there a right way to pass data into a React component from the HTML page?

前端 未结 4 396
悲&欢浪女
悲&欢浪女 2021-01-31 08:29

I have a React app like this.

var X = React.createClass({
  componentDidMount: function() {
    fetch(this.props.feed).then(...);
  }
  render: function() {
             


        
相关标签:
4条回答
  • 2021-01-31 09:00

    I have used data- attributes for various props, then passed all the props using destructuring {...dataset}, for example:

    HTML:

    <div id="app" data-feed='custom_feed.json' data-someprop='value'></div>
    

    JS:

    var root = document.getElementById('app');
    ReactDOM.render(<X {...(root.dataset)} />, root);
    

    Edit: demo fiddle
    Edit 2018: updated fiddle

    0 讨论(0)
  • 2021-01-31 09:01

    I had a similar problem, dynamically generated pages that contain data relevant to the React stuff.

    I just declared them in the global scope ..

    <script>
      window.foobles = [12,453,12];
      window.bahs = ["bah", "bah", "black sheep"];
    </script>
    

    .. THEN ..

    ReactDOM.render(
      <Component
        foobles={window.foobles}
        bahs={window.bah}
      />,
      document.getElementById('app')
    )
    

    Obviously, from a namespacing perspective, this can have some drawbacks :)

    0 讨论(0)
  • 2021-01-31 09:04

    You can just pass your data when mounting the component like so:

    <div id="root"></div>
    <script>
        const data = { foo: 'bar' };
        ReactDOM.render(
            React.createElement(MyComponent, data),
            document.getElementById('root')
        );
    </script>
    
    0 讨论(0)
  • 2021-01-31 09:04

    React Habitat is a framework that facilitates this if you want something reusable and extendable.

    You register React components like this

    containerBuilder.register(Feed).as('Feed')
    

    Then define targets in the HTML like this with props

    <div data-component="Feed" data-prop-feed-src="/custom_feed.json">
    

    React Habitat will wire these up any time it appears in the HTML.

    Disclosure: I am one of the head maintainers of this framework.

    0 讨论(0)
提交回复
热议问题