前面一個文章僚匆,寫了一個內(nèi)置組件并且可以自由定義的組件后憋飞,原理就是內(nèi)置了兩個軟件方法,可以根據(jù)prop傳進去的值進行對應(yīng)的選擇争剿,或者自定義傳進去一個已艰,進行渲染。<p>
我又查資料總結(jié)了一個更加靈(hun)活(luan)的組件寫法蚕苇,這種寫法實在不敢恭維哩掺,自己寫起來都亂,不過功能都實現(xiàn)了涩笤,大家可以看一下嚼吞。然后我把用法寫一下,希望給大家一點啟發(fā)蹬碧。<p>
這里用到一個方式舱禽,是在一個組件BOX上利用<code>.</code>的語法,在其屬性上又添加了一個組件锰茉,調(diào)用的時候就是<code>BOX.child</code>呢蔫,組件BOX內(nèi)可以隨意使用。
/**
* Created by tiantan on 2016/5/31.
*/
import React from 'react';
import ReactDOM from 'react-dom';
//BOX組件
const BOX=React.createClass({
//定義prop類型
propsTypes:{
tittle:React.PropTypes.string,
header:React.PropTypes.string,
body:React.PropTypes.string,
footer:React.PropTypes.string,
classOuterBox:React.PropTypes.string,
classTittle:React.PropTypes.string,
classInnerBox:React.PropTypes.string
},
//定義默認props
getDefaultProps(){
return{
classn:'box'
}
},
getInitialState(){
return{
}
},
//定義一個內(nèi)部方法,當組件有tittle屬性的時候就會觸發(fā)
renderTittle(tittle){
let{
classTittle
}=this.props;
return <h2 className={classTittle}>{tittle}</h2>
},
//內(nèi)部渲染具體組件的容器片吊,用來裝載BOX.child小組件
renderContent(element,role){
//通過結(jié)構(gòu)绽昏,把this.props中的值存入let {}中
let{
classBox
}=this.props;
return <BOX.child role={role} className={classBox}>{element}</BOX.child>
},
render(){
let{
tittle,
header,
body,
footer,
classOuterBox,
classTittle,
classInnerBox,
props,
children
}=this.props;
return <div className={classOuterBox} {...props}>//定義外層樣式
{tittle?this.renderContent(this.renderTittle(tittle)):this.renderContent(header)};
//通過判斷有無傳入tittle來俏脊,進行具體些選擇全谤,如何渲染。
<div classNmae={classInnerBox}>//通過classInnerBox來渲染
{children}
</div>
{this.renderContent(footer,'footer')}爷贫;//渲染頁腳
</div>
}
});
//BOX子組件
BOX.child=React.createClass({
//子組件定義props類型
propsTypes:{
cover:React.PropTypes.string,
element:React.PropTypes.string,
role:React.PropTypes.string
},
//定義默認props
getDefaultProps(){
return{
role:'header'
}
},
render(){
let {
role,
classname,
cover,
props
}=this.props;
//定義背景
if(cover){
var style={
backgroundImage:'url('+cover+')',
}
}
return <span {...props} className={role?role+"style":classname} style={style}>
{this.props.children}
</span>
}
});
export default BOX;
下面是大概幾種樣式
ReactDOM.render(<Box.child classname="headerstyle" >123</Box.child>,document.getElementById('app'));
ReactDOM.render(<Box tittle="標題" classOuterBox="boxContent"></Box>,document.getElementById('app'));
ReactDOM.render(<Box header="this header" classOuterBox="boxContent">123123</Box>,document.getElementById('app1'));