npm run eject //把project的相关配置信息以及依赖信息弹射出来
Babel >= 7.x
npm install --save-dev @babel/plugin-proposal-decorators
babel@6.x
npm install --save-dev babel-plugin-transform-decorators-legacy
Babel >= 7.x
{"plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }],]
}
babel@6.x
"babel": {"plugins": ["transform-decorators-legacy"],"presets": ["react-app"]
},
使用前
import React from 'react';
import {connect} from 'react-redux';
import actions from '../../redux/actions/index';class MyComponent extend React.Component {render() {return (<div className='my-component'>test my component</div>);}
}function mapStateToProps(state) {return {userInfo: state.userInfo};
}function mapDispatchToProps(dispatch) {return {saveUserName: function (userInfo) {dispatch(actions.saveUserName(userInfo))}}
}//如果此处还使用了相关UI框架的话(比如 Ant Design, Material ui),那么下面的代码就会更长变得难以理解
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
使用后
import React from 'react';
import {connect} from 'react-redux';
import actions from '../../redux/actions/index';
import {withStyles} from 'material-ui/styles'function mapStateToProps(state) {return {userInfo: state.userInfo}
}function mapDispatchToProps(dispatch) {return {saveUserName: function (userInfo) {dispatch(actions.saveUserName(userInfo))}}
}const styles = theme => {console.log(theme); //material ui 主题配置信息(可自定义主题)return {'my-component': {color: '#f00',fontSize: pography.pxToRem(20)}}
};@connect(mapStateToProps, mapDispatchToProps) //还可以添加其他装饰器,装饰器会由里之外的顺序执行
//如果使用了material ui 1.x,基本都会用到下面这个装饰器
@withStyles(styles) // 这将会将styles中的样式以props的方式传递进组件(传递进组件的名字为 classes)
class MyComponent extends React.Component {render() {const {classes} = this.props; //获取样式信息return (<div className={classes['my-component']}>test my component</div>);}
}export default MyComponent;
本文发布于:2024-01-30 22:08:10,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170662369323167.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |