State là nơi lưu trữ data trong ReactJs. Khi lập trình chúng ta nên đơn giản hóa state hết mức có thể và hạn chế số lượng components chứa state. Ví dụ nếu chúng ta có 10 components muốn có data từ state, chúng ta nên tạo một component và chứa state của 10 components kia. Using Props Các bạn xem ví dụ dưới đây về 1 component chứa state sử dụng EcmaScript2016 syntax.
Trang 1Bài 4: ReactJS - State trong React
là gì?
State là nơi lưu trữ data trong ReactJs Khi lập trình chúng ta nên đơn giản hóa state hết mức
có thể và hạn chế số lượng components chứa state Ví dụ nếu chúng ta có 10 components muốn có data từ state, chúng ta nên tạo một component và chứa state của 10 components kia
Using Props
Các bạn xem ví dụ dưới đây về 1 component chứa state sử dụng EcmaScript2016 syntax
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>
Trang 2<h2>{this.state.content}</h2>
</div>
);
}
}
export default App;
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
Và ta được kết quả là: