父子組件數(shù)據(jù)關(guān)系與狀態(tài)提升
狀態(tài)提升:兩個(gè)組件(無父子關(guān)系)共享一個(gè)數(shù)據(jù)并同步數(shù)據(jù)變化,即將子組件中的數(shù)據(jù)提升到父組件中進(jìn)行操作和管理,通過 props
傳遞給子組件
類組件調(diào)用(實(shí)例化)的時(shí)候湿痢,組件內(nèi)部的狀態(tài)是唯一且獨(dú)立的,組件之間數(shù)據(jù)不共享
組件嵌套與調(diào)用漓帚,和類組件還是函數(shù)組件沒有關(guān)系
組合與繼承蹬敲、CSS Module
React
目前還沒有發(fā)現(xiàn)有需要組件繼承的需求,因?yàn)橥ㄟ^ children
或者傳遞視圖 React
元素的方式完全可以解決組件組合的問題舶得,props
可以傳遞任何類型的數(shù)據(jù)掰烟,所以組合的方式完全可以替代繼承方案
邏輯部分需要繼承或者共用時(shí),需要自己去寫邏輯抽離的模塊、函數(shù)纫骑、類蝎亚,單獨(dú)進(jìn)行模塊導(dǎo)入使用
// 1. 如果 Container 內(nèi)部有內(nèi)容,React 會(huì)在 props 內(nèi)部增加 children 屬性
// 2. 如果 Container 內(nèi)部有非元素內(nèi)容先馆,children:非元素內(nèi)容发框,如文本
// 3. 如果 Container 內(nèi)部有單個(gè)元素內(nèi)容,children:React 元素對象
// 4. 如果 Container 內(nèi)部有多個(gè)元素內(nèi)容煤墙,childre:[...(React 元素對象)]
// css module 模塊化
import styles from './index.module.css'
class Container extends React.Component {
render() {
return (
<div className={styles.container}>
<div className="header">{this.props.header}</div>
<div className="sidebar">{this.props.sidebar}</div>
<div className="main">{this.props.main}</div>
</div>
);
}
}
class Header extends React.Component {
render() {
return <p>Header</p>;
}
}
class SideBar extends React.Component {
render() {
return <p>SideBar</p>;
}
}
class Main extends React.Component {
render() {
return <p>Main</p>;
}
}
class App extends React.Component {
render() {
return (
<Container header={<Header />} sidebar={<SideBar />} main={<Main />} />
);
}
}
ReactDOM.render(<App />, document.querySelector("#app"));
為什么 JSX 可以通過 props 傳遞視圖元素梅惯、React 元素?
JSX
本質(zhì)上都會(huì)轉(zhuǎn)為 React
元素仿野,視圖通過 props
傳遞的機(jī)制比較像 vue
的插槽(slot
)铣减,React
本身就允許通過 props
傳遞任何類型的數(shù)據(jù)到子組件
function Modal(props) {
return (
<div>
<header>
<h1>{props.modalHeader}</h1>
</header>
<div className="content">{props.children}</div>
</div>
);
}
function Alert(props) {
return (
<Modal modalHeader={props.headerTitle}>
<p>{props.alertText}</p>
</Modal>
);
}
function WelcomeAlert(props) {
return <Alert headerTitle="Alert - 歡迎標(biāo)題" alertText="Alert - 歡迎歡迎"></Alert>;
}
function LoginModal(props) {
return (
<Modal modalHeader="登錄">
// 通過 props 將 JSX 傳遞給子組件
<form action="" method="post">
<p>
<button>登錄</button>
</p>
</form>
</Modal>
);
}
function App() {
return (
<div>
<WelcomeAlert />
<LoginModal />
</div>
);
}
ReactDOM.render(<App />, document.querySelector("#app"));