react withClamp装饰器

时间:2021-09-10 02:37:52

Clamp.js

等待异步数据加载完后在初始化$clamp

withClamp.js

import React, { Component } from "react";

export default function withClamp(selector = ".clamp2", opt = { clamp: 2 }) {
return function(Target) {
return class WithClamp extends Component {
componentDidMount() {
const nodes = document.querySelectorAll(selector);
if (nodes) {
let node;
for (node of nodes) {
window.$clamp(node, opt);
}
}
}
render() {
return <Target {...this.props} />;
}
};
};
}

使用

@withClamp()
class Home extends Component {
render() {
const { classes } = this.props;
return (
<div class={classes.root}>
<Typography className="clamp2"> ...</Typography>
</div>
);
}
}