react-codemirror2 has no CSS effect

前端 未结 2 1767
走了就别回头了
走了就别回头了 2021-01-28 14:36

I added react-codemirror2 to my project but it does not load the css although I import the codemirror.css file, because it is mentioned that css should be applied i

相关标签:
2条回答
  • 2021-01-28 15:15

    I don't know why you met the problem, but it works for me.

    import React, { Component } from "react";
    
    // Import the code mirror component.
    import { Controlled as CodeMirror } from "react-codemirror2";
    
    // The following two imports is for the theme.
    import 'codemirror/lib/codemirror.css';
    import 'codemirror/theme/material.css';
    
    // This import is for the language syntax highlighting.
    import 'codemirror/mode/javascript/javascript.js';
    
    class MyComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
           src: ''
        }
      }
    
      render() {
        let option = {
          mode: 'javascript',
          theme: 'material'
        };
    
        return (
          <div>
            <Controlled
              value={this.state.src}
              option={option}
              onBeforeChange={(editor, data, value) => {
                this.setState({ src: value });
              }}
              onChange={(editor, data, value) => {}}
            />
          </div>
        )
      }
    }
    

    Maybe the problem is here:

    const myOptions = {
      mode: 'xml',
      theme: shade === 'dark' ? 'material' : 'default',
      lineNumbers: true,
    }
    

    You should set the option object in rendering function before return, or set it in constructor() and attach it to this, like this.option = {}.

    0 讨论(0)
  • 2021-01-28 15:16

    Okay this is something which may only happened to me but I post my solution, maybe someday someone have same issue. As I said the problem was not loading the css, I don't know how others handle this issue but I have to copy all styles inside the node_modules/codemirror/lib/codemirror.css into a new css file and put it in some path inside my project. And inside the global.css file of my project I just imported that new created file like @import absolute/path/to/file/codemirror.css; and it worked at least for one case and one theme. I'm sure there is better ways to connect to all css files of codemirror but for now it did the basic thing that I needed.

    0 讨论(0)
提交回复
热议问题