React sử dụng JSX làm quy chuẩn khi lập trình thay cho Java Script thông thường.
Using JSX¶
JSX khá giống với HTML, nên bạn sẽ không mấy khó khăn khi làm quen với nó. Ta cùng xem lại file App.js trong folder src:
App.js
import React from 'react'; class App extends React.Component { render() { return ( <div> Hello World!!! </div> ); } } export default App;
Nhìn rất giống HTML bình thường ta code phải không? Nhưng có vài điều chúng ta cần lưu ý khi làm việc với JSX
Nested Elements¶
Nếu chúng ta muốn return nhiều elements, chúng ta cần bọc nó với 1 container.
App.js
import React from 'react'; class App extends React.Component { render() { return ( <div> <h1>Header</h1> <h2>Content</h2> <p>This is the content!!!</p> </div> ); } } export default App;
JavaScript Expressions¶
JavaScript Expressions có thể được sử dụng trong JSX, ta chỉ cần bao nó với 2 dấu ngoặc nhọn {}
import React from 'react'; class App extends React.Component { render() { return ( <div> <h1>{1+1}</h1> </div> ); } } export default App;
Chúng ta không thể sử dụng If Else trong JSX, thay vào đó ta có thể sử dụng:
import React from 'react'; class App extends React.Component { render() { var i = 1; return ( <div> <h1>{i == 1 ? 'True!' : 'False'}</h1> </div> ); } } export default App;
Styling¶
Để sử dụng inline styles trong React chúng ta nên dùng camelCase syntax. React cũng sẽ tự động thêm 'px' vào sau các giá trị số cho các element, cụ thể như: 'font-size, width, height...' Các bạn xem ví dụ sau:
import React from 'react'; class App extends React.Component { render() { var myStyle = { fontSize: 100, color: '#FF0000' } return ( <div> <h1 style = {myStyle}>Header</h1> </div> ); } } export default App;
Comments¶
Để thêm comments trong React ta làm như sau:
import React from 'react'; class App extends React.Component { render() { return ( <div> <h1>Header</h1> {//End of the line Comment...} {/*Multi line comment...*/} </div> ); } } export default App;