HTML 語言直接寫在 JavaScript 語言之中,不加任何引號,這就是 JSX 的語法,它容許 HTML 與 JavaScript 的混寫。javascript
var names = ['Alice', 'Emily', 'Kate']; React.render( <div> { names.map(function (name) { return <div>Hello, {name}!</div> }) } </div>, document.getElementById('example') );
上面代碼體現了 JSX 的基本語法規則:遇到 HTML 標籤(以 < 開頭),就用 HTML 規則解析;遇到代碼塊(以 { 開頭),就用 JavaScript 規則解析。JSX 容許直接在模板插入 JavaScript 變量。若是這個變量是一個數組,則會展開這個數組的全部成員:css
var arr = [ <h1>Hello world!</h1>, <h2>React is awesome</h2>, ]; React.render( <div>{arr}</div>, document.getElementById('example') );
JSX編譯器的核心是將基於XML的語言編譯成JS代碼,主要是依賴於React.createElment函數。java
var Nav; // Input (JSX): var app = <Nav color="blue" />; // Output (JS): var app = React.createElement(Nav, {color:"blue"});
var Nav, Profile; // Input (JSX): var app = <Nav color="blue"><Profile>click</Profile></Nav>; // Output (JS): var app = React.createElement( Nav, {color:"blue"}, React.createElement(Profile, null, "click") );
若是須要在HTML中混入JavaScript變量值,須要利用{}來代替""。數組
// Input (JSX): var person = <Person name={window.isLoggedIn ? window.name : ''} />; // Output (JS): var person = React.createElement( Person, {name: window.isLoggedIn ? window.name : ''} );
// These two are equivalent in JSX for disabling a button <input type="button" disabled />; <input type="button" disabled={true} />; // And these two are equivalent in JSX for not disabling a button <input type="button" />; <input type="button" disabled={false} />;
// Input (JSX): var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>; // Output (JS): var content = React.createElement( Container, null, window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login) );
JSX 裏添加註釋很容易;它們只是 JS 表達式而已。你只須要在一個標籤的子節點內(非最外層)當心地用 {}
包圍要註釋的部分。app
var content = ( <Nav> {/* child comment, put {} around */} <Person /* multi line comment */ name={window.isLoggedIn ? window.name : ''} // end of line comment /> </Nav> );
在JSX中是不能夠直接在{}中加入if-else的,能夠使用下面這種三元表達式:ide
React.render(<div id={condition ? 'msg' : ''}>Hello World!</div>, mountNode);
不過三元表達式每每並不能知足需求,React建議的方式是在JS代碼中使用if表達式:函數
var loginButton; if (loggedIn) { loginButton = <LogoutButton />; } else { loginButton = <LoginButton />; } return ( <nav> <Home /> {loginButton} </nav> );
<style type="text/css"> .hidden { display:none; } </style> render: function() { return ( <div className={this.props.shouldHide ? 'hidden' : ''}> This will be hidden if you set <tt>props.shouldHide</tt> to something truthy. </div> ); }
return ( <section> <h1>Color</h1> <h3>Name</h3> <p>{this.state.color || "white"}</p> <h3>Hex</h3> <p> {(() => { switch (this.state.color) { case "red": return "#FF0000"; case "green": return "#00FF00"; case "blue": return "#0000FF"; default: return "#FFFFFF"; } })()} </p> </section> );
var rows = []; for (var i=0; i < numrows; i++) { rows.push(<ObjectRow />); } return <tbody>{rows}</tbody>;