首页 > 解决方案 > react-codemirror2 没有 CSS 效果

问题描述

我将react-codemirror2添加到我的项目中,但是尽管我导入了文件,但它没有加载 css codemirror.css,因为它提到 css 应该以某种方式应用到组件中(提到这里),但长话短说它仍然呈现如下: 没有 CSS 的代码镜像

我真的不知道问题是什么。所以这是我的代码:

import { connect } from 'react-redux';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
import { Controlled as CodeMirror } from 'react-codemirror2';
require('codemirror/mode/xml/xml');
require('codemirror/mode/javascript/javascript');

class MyComponent extends Component {
  handleValueChange = value => this.props.onUpdateValue({ value });
  render() {
const { shade } = this.props;
const myOptions = {
      mode: 'xml',
      theme: shade === 'dark' ? 'material' : 'default',
      lineNumbers: true,
    }
return (
  <CodeMirror
    id="editor"
    value={this.props.value}
    options={myOptions}
    onBeforeChange={(editor, data, value) => {
      this.handleValueChange(value);
    }}
    onChange={(editor, data, value) => {}}
  />
);
  }
}

function mapStateToProps(state) {
  return {
    shade: state.muiTheme.shade,
  };
}

export default connect(
  mapStateToProps,
  null
)(MyComponent);

我还尝试了项目文件中@import的 css 文件global.css(如下所示),但没有任何改变。

@import '/node_modules/codemirror/lib/codemirror.css';
@import '/node_modules/codemirror/theme/material.css';

我真的不知道还应该尝试什么或我做错了什么,因为它不应该是非常特别的东西。所以我问你,任何建议都会有所帮助。

谢谢 :)

标签: reactjscodemirrorreact-codemirror

解决方案


我不知道你为什么会遇到这个问题,但它对我有用。

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>
    )
  }
}

也许问题出在这里:

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

您应该在渲染函数之前设置选项对象return,或者将其设置constructor()并附加到this,例如this.option = {}


推荐阅读