Pass props from template into react.js root node

前端 未结 3 2025
日久生厌
日久生厌 2021-01-04 11:03

I may have missed something, but here goes. If I have:

var Swoosh = React.createClass({
  render: function() {
    ret         


        
相关标签:
3条回答
  • 2021-01-04 11:38

    No, though of course you can do:

    var container = document.getElementById('content');
    React.renderComponent(
      <Swoosh
        foo={container.getAttribute('foo')}
        bar={container.getAttribute('bar')}
        bav={container.getAttribute('bav')} />,
      container
    );
    

    (or if you want to make an attributes dict using something like https://stackoverflow.com/a/5282801/49485, then you can do Swoosh(attributes)).

    0 讨论(0)
  • 2021-01-04 11:47

    There is a alternative way to achieve this by using data attributes in html. Here's a small example: In html, you add as much properties with the data prefix as you want:

    <div id="root" data-prop-one="Property one" data-prop-two="Property two"/>
    

    All data properties will be automatically converted to CamelCased properties in the element's dataset property. Pass this property to your React component and you're done:

    let element = document.getElementById('root')
    ReactDOM.render(<App myPropsObject={element.dataset}/>, element)
    
    0 讨论(0)
  • 2021-01-04 11:58

    There's nothing in the API to transfer properties from a plain DOM element to a React component, but you could create a Mixin to do it. Note that this will only work on a component passed to renderComponent because it uses setProps:

    (Working JSFiddle)

    var InheritsDomAttributes = {
      componentDidMount: function(rootNode) {
        var hasNextProps = false;
        var nextProps = {};
        var parentNode = rootNode.parentNode;
    
        Object.keys(parentNode.attributes).forEach(function(key) {
          var namedNode;
    
          // NamedNodeMaps have an attribute named "length" that
          // should not be considered a set attribute.
          if (key !== "length") {
            hasNextProps = true;
            namedNode = parentNode.attributes[key];
            nextProps[namedNode.name] = namedNode.value;
          }
        });
    
        if (hasNextProps) this.setProps(nextProps);
      }
    };
    
    var Swoosh = React.createClass({
      mixins: [InheritsDomAttributes],
      render: function() {
        return (
          <div className="swoosh">
            Boom.
          </div>
        );
      }
    });
    
    React.renderComponent(
      <Swoosh />,
      document.getElementById('content')
    );
    
    0 讨论(0)
提交回复
热议问题