組合與繼承
- 若Container內部有內容,React會在props內部增加children屬性
- 若Container內部有非元素內容,children:非元素內容
- 若Container內部有單個元素內容,children:React元素對象
- 若Container內部有多個元素內容,children:[]
- 打印props
- 情況2:非元素內容
<Container>666</Container>
- 情況3:單個元素內容
<Container><h1>666</h1></Container>
- 情況4:多個元素內容
<Container><h1>666</h1><p>888</p>
</Container>
props
- JSX還可以通過props傳遞視圖元素
- JSX本質上都會轉成React元素(對象 Object)
- 視圖通過props傳遞的機制類似Vue的插槽,但React沒有slot的概念定義
- React本身就允許通過props傳遞任何類型的數據到子組件
React樣式
- CSS Module
- index.module.css
import styles from './index4.module.css'
// 用變量接收
class Container extends React.Component {render() {console.log(this.props)return (<div className={styles.container}><div className={styles.header}>{this.props.header}</div><div className={styles.main}><div className={styles.left}>{this.props.left}</div><div className={styles.right}>{this.props.right}</div></div></div>)}
}
class Header extends React.Component {render() {return <div>Header</div>}
}
class Left extends React.Component {render() {return <div>Left</div>}
}
class Right extends React.Component {render() {return <div>Right</div>}
}
class App extends React.Component {render() {return (<div><Containerheader={<Header />}left={<Left />}right={<Right />}></Container></div>)}
}
ReactDOM.render(<App />,document.getElementById('app')
)
.container {background: #ccc;text-align: center;
}
.header {height: 50px;line-height: 50px;border: 2px dashed #000;
}
.main {display: flex;
}
.left {width: 20%;background: pink;
}
.right {background: skyblue;flex: 1;
}
多層組合
import styles from './index5.module.css'// 多層組合
// Modal是公共的部分,定制的內容作為children傳入
function Modal(props) {return (<div className={styles.wrap}><header className={styles.title}>{props.title}</header><div className="main">{props.children}</div></div>)
}
// 注意函數式 props作為參數傳入 不用this來訪問props
function Alert(props) {return (<div><Modal title={props.title}><p>{props.mainText}</p></Modal></div>)
}
function LoginModal(props) {return (<div><Modal title={props.title}><form><p>用戶名:<input type="text" /></p><p>密碼:<input type="password" /></p><p><button>登錄</button></p></form></Modal></div>)
}
ReactDOM.render(<div><AlertmainText="顯示內容"title="顯示modal"/><LoginModal title="登錄modal"></LoginModal></div>,document.getElementById('app'))
React目前還沒有發現有需要組件繼承的需求
因為通過children或者傳遞視圖React元素的方式完全可以解決組件組合的問題太;
props可以傳遞任何類型的數據,所以組合的方式可以替代繼承方案。
邏輯部分需要繼承或共用:該部分需要自己去編寫邏輯抽離的模塊、函數、類,單獨進行模塊導入使用