ReactJS - State - Props
Trong React, state là các thành phần để xây dựng nên một component.
State là lưu lưu trữ các giá trị của component, khi state thay đổi thì component cũng được render lại.
App.js
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "Header from state...",
content: "Content from state..."
}
}
render() {
return (
<div>
<h1>{this.state.header}</h1>
<h2>{this.state.content}</h2>
</div>
);
}
}
export default App;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App/>, document.getElementById('root'));
Và ta được kết quả là:
Set State
setState()
là method để cập nhật giá trị của state trong component. Nó sẽ không xóa bỏ đi state mà chỉ là thay đổi giá trị của nó.
Update app.js
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
data: []
}
this.setStateHandler = this.setStateHandler.bind(this);
};
setStateHandler() {
var item = "setState..."
var myArray = this.state.data.slice();
myArray.push(item);
this.setState({data: myArray})
};
render() {
return (
<div>
<button onClick = {this.setStateHandler}>SET STATE</button>
<h4>State Array: {this.state.data}</h4>
</div>
);
}
}
export default App;
Ban đầu giá trị của data
là một mảng rỗng. Mối lần người dùng click vào button, giá trị của data
sẽ được thêm vào giá trị mới setState...
. Nếu chúng ta click 3 lần giá trị của data sẽ là: data = ["setState...", "setState...", "setState..."]
.
Props:
Trong ReactJs ngoài state ra còn 1 hình thức lưu giữ data nữa đó là props, vậy props khác state như thế nào? Hiểu đơn giản là state thuộc về component, bạn có thể update, chỉnh sửa state, còn props cũng lưu dữ liệu như state nhưng được nhận từ component cha truyền xuống, bạn không thể chỉnh sửa trực tiếp props mà phải thay đổi từ cha nó. Bạn xem ví dụ sau để hiểu rõ hơn:
App.js
index.js
Nếu bạn so sánh App.js
với bài State, bạn sẽ thấy giờ đây App không còn state để giữ data để truyền vào 2 thẻ h1,h2 nữa mà thay vào đó lấy từ props. Kết quả hiển thị vẫn giống State:
Default Props¶
Bạn có thể set default props cho component thay vì phải truyền vào lúc ReactDom.render()
App.js
index.js
State and Props¶
Ví dụ dưới đây sẽ hướng dẫn bạn cách sử dụng state và props cùng với nhau. Chúng ta sẽ khởi tạo state trong component cha và chuyền nó xuống các components con thông qua props.
App.js
index.js
Và kết quả vẫn không đổi: