将模板中的props传递给react.js根节点

mal*_*ree 10 reactjs

我可能错过了一些东西,但这里有.如果我有:

var Swoosh = React.createClass({
  render: function() {
    return (
      <div className="swoosh">
        Boom.
      </div>
    );
  }
});

React.renderComponent(
  <Swoosh />,
  document.getElementById('content')
);
Run Code Online (Sandbox Code Playgroud)

我可以props在挂载点(where id='content')上设置属性吗?

<div id='content' foo='alice' bar='has' bav='a cat' />
<!-- have foo, bar & bav available as props in <Swoosh />? -->
Run Code Online (Sandbox Code Playgroud)

Sop*_*ert 19

不,当然你可以这样做:

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

(或者如果你想使用像/sf/answers/369796101/这样的属性dict ,那么你可以这样做Swoosh(attributes)).


Ros*_*len 7

API中没有任何内容可以将属性从普通DOM元素传输到React组件,但您可以创建一个Mixin来执行此操作.请注意,这只适用于传递给renderComponent它的组件,因为它使用setProps:

(工作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')
);
Run Code Online (Sandbox Code Playgroud)


Dan*_*ndt 6

还有另一种方法可以通过使用 html 中的数据属性来实现此目的。这是一个小例子:在 html 中,您可以根据需要添加任意数量的带有数据前缀的属性:

<div id="root" data-prop-one="Property one" data-prop-two="Property two"/>
Run Code Online (Sandbox Code Playgroud)

所有数据属性都会自动转换为元素dataset属性中的驼峰命名属性。将此属性传递给您的 React 组件,您就完成了:

let element = document.getElementById('root')
ReactDOM.render(<App myPropsObject={element.dataset}/>, element)
Run Code Online (Sandbox Code Playgroud)