Tải bản đầy đủ (.docx) (6 trang)

Hướng dẫn ReactJS ReactJS tutorial (p5) Bài 5: ReactJS Props Overview

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (65.57 KB, 6 trang )

Bài 5: ReactJS - Props Overview
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
import React from 'react';

class App extends React.Component {
render() {
return (
<div>

{this.props.headerProp}


{this.props.contentProp}


</div>
);
}
}
export default App;

Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';


ReactDOM.render(, document.getElementById('app'));

export default App;


Nếu bạn so sánh App.js với bài 4, 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 bài 4:

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
import React from 'react';

class App extends React.Component {
render() {
return (
<div>

{this.props.headerProp}


{this.props.contentProp}


</div>


);
}
}
App.defaultProps = {
headerProp: "Header from props...",
contentProp:"Content from props..."
}
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'));

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


import React from 'react';

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "Header from props...",
content: "Content from props..."
}
}
render() {
return (
<div>
<Header headerProp = {this.state.header}/>
<Content contentProp = {this.state.content}/>
</div>
);

}
}
class Header extends React.Component {
render() {
return (
<div>

{this.props.headerProp}


</div>
);
}


}
class Content extends React.Component {
render() {
return (
<div>

{this.props.contentProp}


</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à kết quả vẫn không đổi:

Mình kết thúc bài 5 ở đây nha, các bạn xem lại rồi thực hành nhiều lần để hiểu hơn
nha.




×