如何在没有JSX的情况下渲染多个孩子

Dem*_*ier 12 javascript reactjs

如何在不使用JSX的情况下编写此代码?

 var CommentBox = React.createClass({
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList />
        <CommentForm />
      </div>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

这来自react.js教程:http://facebook.github.io/react/docs/tutorial.html

我知道我可以做到以下几点:

return (
   React.createElement('div', { className: "commentBox" },
        React.createElement('h1', {}, "Comments")
)
Run Code Online (Sandbox Code Playgroud)

但这只会增加一个元素.如何在彼此旁边添加更多内容.

Jon*_*nan 16

您可以使用在线Babel REPL(https://babeljs.io/repl/)作为将小块JSX转换为等效JavaScript的快速方法.

var CommentBox = React.createClass({displayName: 'CommentBox',
  render: function() {
    return (
      React.createElement("div", {className: "commentBox"}, 
        React.createElement("h1", null, "Comments"), 
        React.createElement(CommentList, null), 
        React.createElement(CommentForm, null)
      )
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

它还可以方便地检查它支持的ES6变换器的转换器输出.


Bri*_*and 6

insin的答案是直接翻译,但是您可能更喜欢使用工厂。

var div = React.createFactory('div'), h1 = React.createFactory('h1');

var CommentBox = React.createClass({displayName: 'CommentBox',
  render: function() {
    return (
      div({className: "commentBox"}, 
        h1(null, "Comments"), 
        React.createElement(CommentList, null), 
        React.createElement(CommentForm, null)
      )
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

createFactory本质上部分地应用了createElement。所以以下是等效的:

React.createElement(c, props, child1, child2);
React.createFactory(c)(props, child1, child2);
Run Code Online (Sandbox Code Playgroud)

如果您只是使用es6而又不喜欢JSX,则可以通过解构赋值使其变得不那么冗长。看到这个jsbin使用6to5代替JSX一个互动的例子。

var [div, h1, commentForm, commentList] = [
    'div', 'h1', CommentForm, CommentList
].map(React.createFactory);
Run Code Online (Sandbox Code Playgroud)

  • TIL createFactory (2认同)