简体   繁体   English

React和Material-Ui在.js中定义类,并将其作为字符串传递给组件

[英]React and Material-Ui define class in .js and pass it as string to a component

Im trying to define a class inside my .js file, so i can make use of material-uis theme object and pass it as a string to a component as the components prop only accepts strings. 我正在尝试在.js文件中定义一个类,因此我可以利用material-uis主题对象,并将其作为字符串传递给组件,因为components prop只接受字符串。 The React-Dropzone import only accepts a string as a parameter and not a class object. React-Dropzone导入仅接受字符串作为参数,而不接受类对象。

codesandbox: codesandbox:

https://codesandbox.io/s/x74qvqxww4 https://codesandbox.io/s/x74qvqxww4

or: 要么:

import React, { Fragment } from "react";
import Dropzone from "react-dropzone";
import { withStyles } from "@material-ui/core/styles";

const styles = theme => ({
  green: {
    color: "blue"
  }
});

function CustomDropzone(props) {
  return (
    <Fragment>
      <Dropzone acceptClassName="dropzoneAccept" />
      <div className={props.classes.green}>
        Thats how i appy styles normally
      </div>
    </Fragment>
  );
}

export default withStyles(styles, { withTheme: true })(CustomDropzone);

How can i achieve it? 我该如何实现? Importing a .css file works but then the styles in my projects arent consistent. 导入.css文件是可以的,但随后我项目中的样式将保持一致。

Thanks for any help in advance! 感谢您的任何帮助!

All you would need to do is to declare the class like so: 您需要做的就是像这样声明该类:

import React, { Fragment } from "react";
import Dropzone from "react-dropzone";
import { withStyles } from "@material-ui/core/styles";

const styles = theme => ({
  green: {
    color: "blue"
  }
});

class CustomDropzone extends React.Component {
  render() {
    return (
      <Fragment>
        <Dropzone acceptClassName="dropzoneAccept" />
        <div className={this.props.classes.green}>
          Thats how i appy styles normally
        </div>
      </Fragment>
    );
  }
}

export default withStyles(styles, { withTheme: true })(CustomDropzone);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM