react组件设计和分解
2018-05-15 本文已影响5人
YC____
react组件设计和分解
1.切割render
const PanelHeader = (props) => (
// ...
)
const PanelBody = (props) => (
// ...
)
class Panel extends React.Component {
render() {
return (
<div>
<PanelHeader title={this.props.title}/>
<PanelBody content={this.props.content}/>
</div>
);
}
}
2.模块化组件
相当于一个模版,根据传入参数进行不同的渲染
class commentTemplate extends React.Component(){
static propTypes = {
actions:propTypes.node
}
render(){
<div>{this.props.actions}</div>
}
}
class comment extends React.Component(){
render(){
const actions = [];
if(this.props.condition){
actions.push(<Delete/>)
}else{
actions.push(<Add/>)
}
return <commentTemplate actions={actions}/>
}
}
3.高阶组件
高阶组件就是一个函数,且该函数接受一个组件作为参数,并返回一个新的组件
function noId() {
return function(Comp) {
return class NoID extends Component {
render() {
const {id, ...others} = this.props;
return (
<Comp {...others}/>
)
}
}
}
}
const WithoutID = noId()(Comp);