2014-12-04 2 views
11

JSX를 사용하지 않고 이것을 작성하는 방법은 무엇입니까? 이것은 react.js 튜토리얼에서 오는JSX없이 여러 자식을 렌더링하는 방법

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

:

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

을하지만 이것은 단지 하나 개의 요소를 추가 : http://facebook.github.io/react/docs/tutorial.html

은 내가 다음을 수행 할 수 있습니다 알고 있습니다. 서로 어떻게 더 많이 추가 할 수 있습니까?

답변

14

당신은 해당 자바 스크립트에 JSX의 작은 덩어리로 변환하는 빠른 방법으로 온라인 JSX Compiler을 사용할 수 있습니다, 당신의 부모 구성 요소에 대한 어린이와 같은 다른 후 그들에게 하나를 추가 할 수 있습니다.

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/을 사용하십시오 –

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 좋아하지 않은 경우 당신이 destructuring 할당을 덜 장황 할 수 있습니다. jsx 대신 6to5를 사용하는 대화 형 예제는 jsbin을 참조하십시오. 당신이 아이들의 변수 번호가있는 경우

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

TIL createFactory – masonk

2

당신은 그것을 사용할 수 있습니다 를 매개 변수의 배열을 함수를 적용하여. renderLineList는 예를 들어입니다

React.createElement.apply(this, ['tbody', {your setting}].concat(this.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' 그리고 이것이 바로 그것을 고쳤습니다. 나는 화해는 신경 쓰지 않지만, 단지 반응의 dev 버전에서 경고를 원했다. – Noitidart

관련 문제