React - Khi nào nên dùng Component, khi nào nên dùng Element

Mình thấy trong React có 2 loại, 1 là Element, 2 là Component. Vậy khi nào dùng element, khi nào dùng component nhỉ
Ví dụ trong ví dụ về todo của redux:

const Todo = ({ onClick, completed, text }) => (
  <li
    onClick={onClick}
    style={{
      textDecoration: completed ? 'line-through' : 'none'
    }}
  >
    {text}
  </li>
)

Todo.propTypes = {
  onClick: PropTypes.func.isRequired,
  completed: PropTypes.bool.isRequired,
  text: PropTypes.string.isRequired
}

Mình thử chuyển nó sang component:

class Todo extends React.Component {
  render() {
    return (
      <li
        onClick={this.props.onClick}
        style={{
        textDecoration: this.props.completed
          ? 'line-through'
          : 'none'
      }}>
        {this.props.text}
      </li>
    )
  }
}

thì vẫn không thấy gì khác biệt :grin:

Kinh nghiệm của mình bên React Native thì dùng Element nếu muốn làm gì đó nhanh gọn lẹ, dùng Component khi muốn làm một “Component” với đầy đủ tính năng, dễ quản lý, bảo trì :sweat_smile:

1 Like

Nếu bạn làm giùm mình so sánh chi tiết thì tốt quá. :grin:


Theo như cái này thì: element là đơn vị nhỏ nhất của UI, immutable; component thì bọc nó, thêm phần quản lý (state, update…), trường hợp muốn tạo lẹ 1 ui nào đó thì dùng element để tiết kiệm thời gian chạy; cũng có thể return element làm nguyên liệu cho một hàm render nào đó (thay vì viết một hàm render khổng lồ.

1 Like

Sau khi nghiên cứu kĩ thì mình mới nhận ra mình bị nhầm lẫn giữa 2 khái niệm là Element và Stateless functional components:
Element:
Element = <li>Element </li>
Stateless functional components:
Component = ()=> <li>Element</li>

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?