-
render: Là hàm chính để render các element của component. -
constructor: Là hàm khởi tạo khi một component được tạo ra. -
componentDidMount: Là một lifecycle method được gọi sau khi component đã được mount. -
shouldComponentUpdate: Là một lifecycle method được gọi trước khi một component được render lại. -
componentDidUpdate: Là một lifecycle method được gọi sau khi component đã được render lại. -
componentWillUnmount: Là một lifecycle method được gọi trước khi component được unmount. -
setState: Là hàm để cập nhật trạng thái (state) của component. -
forceUpdate: Là hàm để yêu cầu component render lại, mặc dù hàmshouldComponentUpdatetrả về false. -
props: Là object chứa tất cả các thuộc tính (props) truyền vào component từ component cha. -
state: Là object chứa trạng thái của component. -
defaultProps: Là object chứa các giá trị mặc định cho các thuộc tính (props) của component. -
context: Là object chứa các giá trị được truyền xuống từ component cha tới tất cả các component con. -
ref: Là một tham chiếu đến element DOM hoặc instance của component đang được render.
Ví dụ:
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props, context) {
super(props);
this.state = {
message: 'Hello World!'
};
this.myRef = React.createRef();
this.context = context;
}
componentDidMount() {
console.log('My component has been mounted');
console.log('Context: ', this.context);
}
componentWillUnmount() {
console.log('My component will be unmounted');
}
shouldComponentUpdate(nextProps, nextState) {
if (this.state.message !== nextState.message) {
return true;
}
return false;
}
componentDidUpdate(prevProps, prevState) {
console.log('My component has been updated');
}
handleClick = () => {
this.setState({
message: 'Hello React!'
});
};
handleForceUpdate = () => {
this.forceUpdate();
};
render() {
return (
<div ref={this.myRef}>
<h1>{this.state.message}</h1>
<button onClick={this.handleClick}>Update State</button>
<button onClick={this.handleForceUpdate}>Force Update</button>
</div>
);
}
}
MyComponent.contextType = {
theme: PropTypes.string
};
export default MyComponent;
Ngoài các API trên là các API thường được sử dụng nhiều nhất thì React còn nhiều loại API chúng ta sẽ tìm hiểu sau nhé.