We want to hear from you!Take our 2021 Community Survey!
This site is no longer updated.Go to react.dev

React Không Dùng JSX

These docs are old and won’t be updated. Go to react.dev for the new React docs.

JSX không phải là một yêu cầu bắt buộc để sử dụng React. Sử dụng React mà không dùng JSX đặc biệt thuận tiện khi bạn không muốn thiết lập compilation trong môi trường build của bạn.

Mỗi phần tử JSX chỉ là một syntactic sugar để gọi React.createElement(component, props, ...children). Vì vậy, bất cứ điều gì bạn có thể làm với JSX thì cũng có thể thực hiện được chỉ với JavaScript đơn giản.

Ví dụ, đoạn code này được viết bằng JSX:

class Hello extends React.Component {
  render() {
    return <div>Hello {this.props.toWhat}</div>;
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Hello toWhat="World" />);

có thể được biên dịch thành đoạn code bên dưới, không sử dụng JSX:

class Hello extends React.Component {
  render() {
    return React.createElement('div', null, `Hello ${this.props.toWhat}`);
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(Hello, {toWhat: 'World'}, null));

Nếu bạn tò mò muốn xem thêm các ví dụ về cách JSX được chuyển đổi sang JavaScript, bạn có thể thử trình biên dịch Babel online.

Component có thể được cung cấp dưới dạng một string, dưới dạng subclass của React.Component hoặc một function thuần túy.

Nếu bạn cảm thấy mệt mỏi với việc gõ React.createElement quá nhiều, một pattern phổ biến là hãy gán cho một biến và dùng nó như dạng viết tắt:

const e = React.createElement;

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(e('div', null, 'Hello World'));

Nếu bạn sử dụng dạng viết tắt này cho React.createElement, thì việc sử dụng React mà không có JSX có thể rất thuận tiện.

Ngoài ra, bạn có thể tham khảo các dự án cộng đồng như react-hyperscripthyperscript-helpers sẽ cung cấp cho bạn cú pháp ngắn gọn hơn.

Trang này có hữu ích không?Sửa trang này