admin管理员组

文章数量:1178552

I am trying to set a style for a component, but I do not know how to write the correct syntax in React. My CSS looks like this:

 .cell {
   border: 1px solid rgba(0, 0, 0, 0.05);
 }

And here is my render() method:

 render() {
   let styles = {
        ...

       //border: 1px solid rgba(0, 0, 0, 0.05),  <---- Not correct
   };
   return (
     <div className="cell" style={styles}></div>
   );
 }

How do I convert the CSS syntax into a React/JS syntax ?

I am trying to set a style for a component, but I do not know how to write the correct syntax in React. My CSS looks like this:

 .cell {
   border: 1px solid rgba(0, 0, 0, 0.05);
 }

And here is my render() method:

 render() {
   let styles = {
        ...

       //border: 1px solid rgba(0, 0, 0, 0.05),  <---- Not correct
   };
   return (
     <div className="cell" style={styles}></div>
   );
 }

How do I convert the CSS syntax into a React/JS syntax ?

Share Improve this question edited Apr 25, 2020 at 0:15 Toms River asked Apr 25, 2020 at 0:05 Toms RiverToms River 3661 gold badge5 silver badges16 bronze badges 1
  • you can access this for some reference w3schools.com/react/react_css.asp – Shaurya Vardhan Singh Commented Apr 25, 2020 at 0:11
Add a comment  | 

6 Answers 6

Reset to default 25

Here is the thing:

render() {
   const styles = {
        border: '1px solid rgba(0, 0, 0, 0.05)', 
   };

   return (
     <div style={styles}>Hello</div>
   );
 }

if you want to write it like inline it must be like this

render() {
   return (
     <div style={{border: '1px solid rgba(0, 0, 0, 0.05)'}} >Hello</div>
   );
 }

For eg:

const divStyle = {
  color: 'blue',
  backgroundImage: 'url(' + imgUrl + ')',
};
function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!</div>;

border: '1px solid rgba(0, 0, 0, 0.05)',

You need declare value in string using 'to declare a CSS property

Since styles is an object, you should write border: '1px solid rgba(0, 0, 0, 0.05)'.

It is usually in camelCase. Example background-color: "white" will be written as backgroundColor: "white"

It is better to keep your css separate from the component itself for readability and debugging sake. Say your component name is MyComponent.js on the same level as this file is create a file MyComponent.module.css in here place your styles like you would in a normal css file like:

 .cell {
   border: 1px solid rgba(0, 0, 0, 0.05);
 }

Then import this in MyComponent.js as :

import styles from ./MyComponent.module.css

then wherever you need to use it simply do :

 <div className={styles.cell}></div>

This way your css and js is now separate and you can write your css as you normally would.

本文标签: javascriptreactjshow to set style of borderStack Overflow