react中的@方法名/组件名,是什么意思?

如图,上面引入组件后,下面使用@加上组件名是什么意思?

clipboard.png

import React from 'react'
import ReactDom from 'react-dom'
import queryString from 'query-string'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Slide from 'components/slide'
import Scroll from 'components/scroll'
import Toast from 'components/toast'
import { homeUpdate, homeInit, homeList } from '../../stores/home'
import withTabBar from '../common-components/tab-bar'
import TitleBar from '../common-components/title-bar'
import ShopListRow from '../common-components/shop-list-row'
import Skeleton from './skeleton-screen'
import TopBar from './top-bar'
import styles from './index.less'

const mapStateToProps = ({ home }) => ({
    init: home.init,
    banner: home.banner,
    entry: home.entry,
    locationInfo: home.locationInfo,
    shoplist: home.shoplist,
})
const mapActionsToProps = dispatch => bindActionCreators({
    homeUpdate,
    homeInit,
    homeList,
}, dispatch)

@connect(
    mapStateToProps,
    mapActionsToProps,
)
@withTabBar
export default class Home extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            topBarHeight: 0,
        }
    }
    省略......
}
阅读 7.7k
5 个回答

装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

https://blog.csdn.net/wangron...

装饰器模式,在不改变对象的结构的前提下,给指定现有的对象添加新功能。

如问题中描述代码

@connect(
    mapStateToProps,
    mapActionsToProps,
)
@withTabBar
export default class Home extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            topBarHeight: 0,
        }
    }
    省略......
}

这个@withTabBar和@connect(mapStateToProps, mapActionsToProps)可以解析为如下

class Home extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            topBarHeight: 0,
        }
    }
    省略......
}

Home = withTabBar(Home);
Home = connect(mapStateToProps, mapActionsToProps)(Home);

export default Home;

指定组件,然后执行已该组件作为参数的函数,该函数返回新的一个组件。这里的connect大概就是执行函数缓存mapStateToProps,mapActionsToProps并返回一个新的函数,然后利用mapStateToProps,mapActionsToProps给组件返回新的props,同时也保持原有的props。

ES6 的装饰器

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题