📅  最后修改于: 2023-12-03 14:44:14.548000             🧑  作者: Mango
React is a popular Javascript library used for building user interfaces. It was developed by Facebook and is used by many large companies such as Instagram, Netflix, and Airbnb.
To get started with React, you will need to have some knowledge of Javascript and HTML. React renders user interfaces using a combination of Javascript and HTML.
You can install React using npm, which is a package manager for Javascript.
To install React, run the following command:
npm install react
Once you have installed React, you can start building your first React component. A component is a reusable piece of code that defines how an element should be rendered.
Here is an example of a simple React component:
import React from 'react'
function MyComponent() {
return <h1>Hello, world!</h1>
}
export default MyComponent
In this example, we have defined a component called MyComponent
that simply displays a Hello, world!
message.
JSX is a syntax extension for Javascript that allows you to write HTML-like code in your Javascript. It is used heavily in React to define the structure of components.
Here is an example of JSX:
const element = <h1>Hello, world!</h1>
In this example, we are defining a variable called element
that is a React element. The element contains a h1
tag with the text Hello, world!
.
Props is short for properties and is a way to pass data between components in React.
Here is an example of a component using props:
import React from 'react'
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>
}
export default Greeting
In this example, we have defined a component called Greeting
that takes a prop called name
. The component then displays a message that says Hello, {props.name}!
.
State is a way to store data within a component in React. When the state of a component changes, React will automatically re-render the component.
Here is an example of a component using state:
import React, { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0)
function handleClick() {
setCount(count + 1)
}
return (
<div>
<h1>Count: {count}</h1>
<button onClick={handleClick}>Increment</button>
</div>
)
}
export default Counter
In this example, we have defined a component called Counter
that uses state to keep track of a count. The component also defines a handleClick
function that will increment the count when a button is clicked.
React is a powerful Javascript library that can be used to build complex and dynamic user interfaces. It is important to have a good understanding of Javascript and HTML before diving into React, but with practice, you can create amazing user interfaces.