react之装饰器的安装及使用

mac2024-06-03  42

装饰器的作用:不学不知道,一学吓一跳。装饰器到底有什么用呢? 它用处可就大了,一句话总结就是它是先走的,它放在谁的头上都是先执行装饰器函数然后再指定当前的函数,那么装个装饰器就可以对对象中的state,props进行修改,直接影响就是展示效果,

create-react-app默认不支持装饰器的,需要做以下配置。 1.运行npm run eject,暴露项目的配置项,如果失败的话,则运行

git add… git commit -m “message”

2.安装babel插件

npm install --save-dev @babel/plugin-proposal-decorators

3.修改package.json文件的babel配置项

"babel": { "plugins": [ ["@babel/plugin-proposal-decorators", { "legacy": true }] ], "presets": [ "react-app" ] }

至此,就可以在项目中使用装饰器了

使用呢?直接上例子,下面展示的是带参数装饰器和不带参数装饰器

import React, {Component} from 'react' const MyContainer = ( WrappedComponent ) => { return class demo extends Component { render() { const newProps = {'race': '汉'} return <WrappedComponent {...this.props} {...newProps}/> } } } const ChangeStyle = (props) => WrappedComponent => { return class demo extends Component { render() { return <WrappedComponent {...this.props} {...props}/> } } } const styles = color => { return { 'Color': { color: color } } } @MyContainer @ChangeStyle(styles('red')) class Children1 extends Component { // eslint-disable-next-line no-useless-constructor constructor(props) { super(props) } render() { const { tableData } = this.props return( <div> <table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>民族</th> </tr> </thead> <tbody> { tableData.map((item, index) => <tr key={index} style={{...this.props.Color}}><td>{item.name}</td><td>{item.age}</td><td>{item.sex}</td><td>{this.props.race}</td></tr>) } </tbody> </table> </div> ) } } export default class Test2 extends Component { constructor(props) { super(props) this.state = { tableData: [ {'name': '小明','age': 18, 'sex': '男'}, {'name': '小张','age': 18, 'sex': '男'}, {'name': '小李','age': 18, 'sex': '男'} ] } } changeName = () => { let tableData = this.state.tableData tableData.push({'name': '小杨','age': 18, 'sex': '男'}) this.setState({tableData: tableData}) } render() { return ( <div> <Children1 {...this.state}></Children1> <button onClick={this.changeName}>添加</button> </div> ) } }

大家可以对这个例子进行研究下,看看我的两个装饰器分别实现了什么功能!!!

最新回复(0)