简体   繁体   中英

Javascript reactJs css in javascript in external file

I am using reactjs and trying to get me css inside javascript and finally read the css from an external js file.

Here is the code:

import React from 'react';
import ReactDOM from 'react-dom';

var styles = {
  container: {
    padding: 20,
    border: '5px solid green',
    borderRadius: 2
  }
};

var myComponent = React.createClass({
  render: function() {
    return (
      <div style={styles.container}>
        {this.props.name}
      </div>
    );
  }
});

This works fine but what I need to do is to put the css in an external file. So I've created a file called general.css.js

And I tried to import it:

import styles from './components/general.css';

I add this import to the top of the page with the other imports.

The problem is that it's not reading the styles.

What I'm I doing wrong here?

Make a new file and put this code in it.

export const style = { container : { 
  padding: 20,
  border: '5px solid green', 
  borderRadius: 2 } 
};

Now in your component file.

import * as styles from './style/location/filename'

Now you can use styles in your render function.

return (
    <div style={styles.style.main}>
      <h3 style={styles.style.header}>Vote for your favorite hack day idea</h3>
    </div>
  );

You can directly import your css file in js.

import './style/app.css';

app.css

.page { background-color:#fafafa; }

and you can use this class in React component like below.

<div className="page">

Hope it works!!!!

There is a little tool that automates translation from CSS to JSON representation.

Worth checking that out.

Note how the translation adds _ underscores:

div.redcolor { color:red; }
div:hover { color:blue; }

Into:

{"div_redcolor":{"color":"red"},"div_hover":{"color":"blue"}}

Note how the Vishwas Chauhan used starred method of ES6 import export:

在此处输入图片说明

In case you use this tool you get one big object, and you can use any method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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