3 个答案:
答案 0 :(得分:1)
这是一些技巧,但可以满足您的要求。
import React, {Component} from 'react';
class Sample extends Component {
constructor(props) {
super(props);
this.state = {
style: {
display: "flex",
flexDirection: "column"
},
}
}
getStyle(){
let styled = '{';
Object.keys(this.state.style).forEach(e => {
let key = e.split(/(?=[A-Z])/).join('-').toLowerCase()
styled += `${key}:${this.state.style[e]};`
});
styled += '}'
return styled;
}
render() {
const {style} = this.state;
return (
);
}
}
export default Sample;
答案 1 :(得分:0)
最好的方法是将webpack配置为将CSS提取到新文件中。
npm install extract-text-webpack-plugin --save-dev
npm install style-loader css-loader --save-dev
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
new ExtractTextPlugin("styles.css"),
]
}
答案 2 :(得分:0)
我遇到了ReactJS ref文档。我尝试了以下方法。它按我预期的那样工作。 Demo
import React, { Component } from "react";
class Sample extends Component {
constructor(props) {
super(props);
this.itemContainerRef = React.createRef();
this.state = {
style: {
display: "flex",
flexDirection: "column"
},
itemContainerCSS: {}
};
}
componentDidMount() {
this.setState({
itemContainerCSS: this.itemContainerRef.current.style.cssText || {}
});
}
render() {
const { style, itemContainerCSS } = this.state;
return (
);
}
}
export default Sample;