美文网首页
react组件设计和分解

react组件设计和分解

作者: YC____ | 来源:发表于2018-05-15 21:59 被阅读5次

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);

相关文章

网友评论

      本文标题:react组件设计和分解

      本文链接:https://www.haomeiwen.com/subject/zwtudftx.html