2014-12-04 68 views
11

如何在不使用JSX的情況下編寫此代碼?如何在沒有JSX的情況下渲染多個孩子

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

這個來自react.js教程:http://facebook.github.io/react/docs/tutorial.html

我知道我能做到以下幾點:

return (
    React.createElement('div', { className: "commentBox" }, 
     React.createElement('h1', {}, "Comments") 
) 

但是,這只是增加了一個元素。我怎樣才能添加更多的相鄰。

回答

14

您可以使用在線JSX Compiler作爲一個快速的方法來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) 
    ) 
    ); 
    } 
}); 

這對檢查轉換器輸出的ES6轉換支持的功能也很方便。

+1

JSX編譯器似乎過時。使用https://babeljs.io/repl/ – 2016-09-22 19:07:11

0

你只需要添加他們陸續爲孩子的父組件,

return React.createElement("div", null, 
     React.createElement(CommentList, null), 
     React.createElement(CommentForm, null) 
    ); 
4

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

createFactory本質上部分應用createElement。所以下面的是等價的:

React.createElement(c, props, child1, child2); 
React.createFactory(c)(props, child1, child2); 

如果你僅僅使用ES6但不喜歡JSX的你可以把它與解構賦值更簡潔。有關使用6to5而不是jsx的交互式示例,請參閱此jsbin

var [div, h1, commentForm, commentList] = [ 
    'div', 'h1', CommentForm, CommentList 
].map(React.createFactory); 
+1

TIL createFactory – masonk 2015-07-31 18:04:45

2

,如果你有一個可變數量的孩子,那麼你可以使用: 使用應用內搭的參數數組功能。

React.createElement.apply(this, ['tbody', {your setting}].concat(this.renderLineList())) 

其中renderLineList是例如:

renderLineList: function() { 
     var data=this.props.data; 
     var lineList=[]; 
     data.map(function(line) { 
      lineList.push(React.createElement('tr', {your setting})); 
     }); 
     return lineList; 
    } 
+0

非常感謝您分享這個'.apply'方法,我不斷收到警告'「警告:數組或迭代器中的每個孩子都應該有一個唯一的」密鑰「prop。檢查'ToolbarButton'的渲染方法,請參閱https://fb.me/react-warning-keys瞭解更多信息。」 react.dev.js:18780:9',這是修復它。我不在乎和解,而只是想在react.js的dev版本中發出警告來關閉哈哈 – Noitidart 2015-12-20 13:16:42

相關問題