javascript
如何在React JS组件和React JS App中添加CSS样式?
In this tutorial, we will only work with CSS styles. Please ensure you have basic knowledge of HTML, CSS, React JS and Node.Js.
在本教程中,我們將僅使用CSS樣式 。 請確保您具有HTML,CSS,React JS和Node.Js的基礎知識。
In our recent articles, we talked about React JS components and how to add components in other files?
在最近的文章中,我們討論了React JS組件以及如何在其他文件中添加組件 ?
We said the first step to adding a component from an external component is to import the file into the main component.
我們說從外部組件添加組件的第一步是將文件導入到主要組件中。
Adding a CSS file in our React JS app is also as simple as importing a file in the React JS App.
在我們的React JS應用程序中添加CSS文件也與在React JS應用程序中導入文件一樣簡單。
Let's dive into our code.
讓我們深入研究我們的代碼。
Create a CSS file in the same folder with your component's file.
在與組件文件相同的文件夾中創(chuàng)建一個CSS文件。
index.css
index.css
body {color: blue; }table {border-collapse: collapse;width: 50%; }th, td {text-align: left;padding: 8px; }tr:nth-child(even) {background-color: #f2f2f2 }th {background-color: yellow;color: green; }.go {background-color: lightblue }#form {input[type=text]:focus {background-color: lightblue;} }Let's add some code in our main component file,
讓我們在主要組件文件中添加一些代碼,
App.js:
App.js:
import React from "react" class App extends React.Component {render (){return (<div className = "go"><center><h1> React is Cool!</h1><table><tr><th>Course</th><th>Day</th><th>Coeff</th></tr><tr><td>Algorithm</td><td>monday</td><td>5</td></tr><tr><td>Database</td><td>friday</td><td>4</td></tr></table><hr/></center></div>)} } export default AppFinally, our index.js where we will import our CSS file using the import keyword followed by the name of our CSS file.
最后,在我們的index.js中 ,我們將使用import關鍵字和CSS文件名來導入 CSS文件。
import React from "react" import ReactDOM from "react-dom" import App from "./App" import "./index.css" ReactDOM.render ( <App /> , document.getElementById('root'))Also, adding style to a class is simply by adding the class name in your CSS code. I know you may wonder why I gave used className to assign an attribute to my div.
此外,只需在CSS代碼中添加類名稱即可為類添加樣式 。 我知道您可能想知道為什么我要使用className為div分配一個屬性。
That's the right syntax actually because we are writing JavaScript.
實際上,這是正確的語法,因為我們正在編寫JavaScript。
Run your app and open in browser...
運行您的應用并在瀏覽器中打開...
Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question.
感謝您與我編碼! 下次見。 隨意發(fā)表評論或問題。
翻譯自: https://www.includehelp.com/react-js/how-to-add-css-style-in-react-js-components-and-react-js-app.aspx
總結
以上是生活随笔為你收集整理的如何在React JS组件和React JS App中添加CSS样式?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦之蓝6多少钱一瓶啊?
- 下一篇: 如何检查数组是否包含JavaScript