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.
在与组件文件相同的文件夹中创建一个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 App
Finally, 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.
感谢您与我编码! 下次见。 随意发表评论或问题。
翻译自: https://www.includehelp.com/react-js/how-to-add-css-style-in-react-js-components-and-react-js-app.aspx