Props and state
1. Props

Props là cách truyền dữ liệu từ component cha đến component con.

Component con giao tiếp với component cha sẽ qua việc Emit events
Cách dùng
Component cha truyền dữ liệu cho component con
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
Component con nhận dữ liệu trừ Props và tiến hành xử lý
function Welcome(props){
return <h1>Hello, {props.name}</h1>
}
2. State
State là một object chứa dữ liệu hoặc thông tin về component.
Các thao tác với state
Khởi tại state
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
//Chỉ định một state
this.state = { website: "Freetuts.net" };
}
render() {
return (
<div>
<h1>Học ReactJS căn bản tại {this.state.website} </h1>
</div>
);
}
}
export default App;
Update State
this.setState({
name : 'newValue'
})
hoặc
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
3. React Lifecycle

React có 3 trạng thái:
Mounting : khi được thêm vào DOM
Unmounting : khi bị Remove khỏi DOM
Updating : making changes to nodes already in the DOM
4. Handle an event
Sự khác biệt giữa HTML và React
For example, the HTML:
<button onclick="activateLasers()">
Activate Lasers
</button>
is slightly different in React:
<button onClick={activateLasers}> Activate Lasers
</button>
2 cách để nhận biết event: nguyên nhân this trong html sẽ là window chứ không phải class hiện tại.
Sử dụng binding
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
Sử dụng arrow function
handleClick = () => {
console.log('this is:', this);
}
Sử dụng arrow function in callback
onClick={() => this.handleClick()}
Vấn đề passing arguments to Event Handler
Inside a loop, it is common to want to pass an extra parameter to an event handler. For example, if id
is the row ID, either of the following would work:
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
Last updated
Was this helpful?