Class component là một component được tạo từ class.
Một class component sẽ là một lớp dẫn xuất từ lớp React.Component
. Trong class component cần có hàm render
và có thể có contructor
.
import React from 'react'
class ClassComponent extends React.Component {
constructor(props){
// The code inside the constructor run before any other code
super(props)
}
render() {
return <tag>Content</tag>
}
}
Có một cách ngắn gọn hơn để viết class component, đó là import sẵn lớp Component
trước khi sử dụng:
import React, { Component } from 'react'
class ClassComponent extends Component{
//...
}
Info
Trước phiên bản 16.8.0 của React, chỉ có class component mới có trạng thái (state) và life-cycle methods, cho phép chúng ta lưu trạng thái vào trong component.
Tuy nhiên vào năm 2018 khi mà React phiên bản 16.8.0 được ra mắt, functional component cũng có thể có state và các life cycle method nhờ sử dụng hook. Việc sử dụng functional component kể từ đó cũng trở nên phổ biến hơn.
Related
list
from [[Class Component]]
sort file.ctime asc