天天看點

React 第十一章 元件的組合使用

在之前元件之前都是通過父元件的render中進行合并傳回為一個整體元件,單個元件相對外部都是互相獨立的。

本節将會介紹元件之間的組合,如包裹關系、通過props傳遞元件進行内部組合等

1,通過元件标簽進行包裹子元件實作組合,在元件内部通過this.props.children 特殊屬性進行擷取,如:

import React from 'react';
import ReactDOM from 'react-dom';

//React推薦使用組合而非繼承來實作元件間的代碼重用。
class Window extends React.Component{
	constructor(props){
		super(props);
	}
	
	render(){
		return(
			<div style={{border:"5px solid #ccc"}}>
				{this.props.children}
			</div>
		);
	}
}

ReactDOM.render(<Window>
This is Mgs Window!
</Window>,document.getElementById('root'));
           
React 第十一章 元件的組合使用

2,通過屬性傳遞元件,比如我們要實作一個聊天視窗,我們需要将左側聯系人清單元件和右側聊天界面合并為一個元件,此時我們可以将聯系人元件、以及聊天視窗作為父元件的屬性傳入,在父元件的render中可以進行自由組合,代碼如下:

import React from 'react';
import ReactDOM from 'react-dom';

//React推薦使用組合而非繼承來實作元件間的代碼重用。
class Window extends React.Component{
	constructor(props){
		super(props);
	}
	
	render(){
		return(
			<div style={{border:"5px solid #ccc"}}>
				{this.props.children}
			</div>
		);
	}
}

//聯系人
class Contacts extends React.Component{
	constructor(props){
		super(props);
	}
	render(){
		return(<div>聯系人清單</div>);
	}
}

class ChatWindow extends React.Component{
	constructor(props){
		super(props);
	}
	render(){
		return(<table>
			<tr>
				<td>{this.props.left}</td>
				<td>{this.props.right}</td>
			</tr>
		</table>);
	}
}
var winObj =  <ChatWindow left={<Contacts />} right={<Window>聊天視窗</Window>} />;

ReactDOM.render(winObj,document.getElementById('root'));
           

3,另外也可以通過對子元件進行再次封裝包裹成為新的元件,如:

import React from 'react';
import ReactDOM from 'react-dom';

//React推薦使用組合而非繼承來實作元件間的代碼重用。
class Window extends React.Component{
	constructor(props){
		super(props);
	}
	
	render(){
		return(
			<div style={{border:"5px solid #ccc"}}>
				{this.props.children}
			</div>
		);
	}
}

class WelcomeWindow extends React.Component{
	
	constructor(props){
		super(props);
	}
	
	render(){
		return (
				<div>
					{this.props.title}
					<Window >
						{this.props.msg}
					</Window>	
				</div>
		);
	}
}

ReactDOM.render(<WelcomeWindow title="歡迎你" msg="歡迎來到這裡。。" />,document.getElementById('root'));
           

繼續閱讀