Cú pháp spread {...props} cho phép truyền toàn bộ các thuộc tính của một object JavaScript làm các props riêng lẻ cho một component.
Ví dụ:
const btnProps = { color: "blue", disabled: true, type: "submit" };
// Sử dụng spread:
<Button {...btnProps} />
// Nó hoàn toàn tương đương với việc viết thủ công:
<Button color="blue" disabled={true} type="submit" />Khi nào nên dùng:
- Rất hữu ích khi xây dựng các component wrapper (như Modal, Layout, Input custom) cần "forward" (chuyển tiếp) mọi props thừa (rest props) xuống thẻ HTML thực tế bên dưới.
Cảnh báo:
Cần cẩn thận khi dùng vì nó làm luồng dữ liệu trở nên mờ nhạt (implicit), bạn có thể vô tình rò rỉ (leak) những props không mong muốn xuống DOM gây ra lỗi cảnh báo của React.
The spread syntax {...props} allows you to pass all the properties of a JavaScript object as individual props to a component.
Example:
const btnProps = { color: "blue", disabled: true, type: "submit" };
// Using spread:
<Button {...btnProps} />
// This is strictly equivalent to writing manually:
<Button color="blue" disabled={true} type="submit" />When to use it:
- Highly useful when building wrapper components (like a custom Input, Modal, or Layout) that need to "forward" all extra props (rest props) down to the underlying HTML element.
Warning:
Use it sparingly as it makes the data flow implicit. You might accidentally leak unintended or invalid props down to the DOM, causing React console warnings.