react Mixin混淆组件HOC高阶组件

/* 自定义 mixins */

const customMixin = { 
  componentDidMount(){
    console.log( '------componentDidMount------' )
  },
  say(){
    console.log(this.state.name)
  }
}
function componentClassMixins(Component,mixin){ /* 继承 */
  for(let key in mixin){
    Component.prototype[key] = mixin[key]
  }
}

class Index extends React.Component{
  constructor(){
    super()
    this.state={  name:'alien' }
  }
  render(){
    return  hello,world
       to say 

  }
}
//merge
componentClassMixins(Index,customMixin)

class继承强化组件

//基础组件
class Base extends React.Component{
  constructor(){
    super()
    this.state={
      name:'alien'
    }
  }
  say(){
    console.log('base components')
  }
  render(){
    return  hello,world 点击  

  }
}
//引入基础组件
class Index extends Base{
  componentDidMount(){
    console.log( this.state.name )
  }
  say(){ /* 会覆盖基类中的 say  */
    console.log('extends components')
  }
}
export default Index

HOC(高阶组件)
例如登录加载问题

function withAdminAuth(Comp) {
    return class extends React.Component {
        constructor(props){
            super(props)
            this.state = {
                isAdmin: false,
            }
        } 
        async componentWillMount() {
            const currentRole = await getCurrentUserRole();
            this.setState({
                isAdmin: currentRole === 'Admin',
            });
        }
        render() {
            if (this.state.isAdmin) {
                return ;
            } else {
                return (
您没有权限查看该页面,请联系管理员!
); } } }; }

你可能感兴趣的:(js,JavaScript,react.js,javascript,前端)