Quick Start – React (docschina.org)
React components must start with a capital letter, while HTML tags must be lowercase.
Write tags using JSX
- JSX is stricter than HTML. must close tag
- Cannot return multiple JSX tags, they must be wrapped in a shared parent (a root element)
- If you have a lot of HTML that needs to be ported to JSX, you can use an online converter .
add style
- Use
className
specified
<img className="avatar" />
Display Data
- brace wrap
- Use curly braces instead of quotes when escaping JSX attributes to JavaScript
# 标签内容
return {
<h1> {
user.name } </h1>}
# 属性
return {
<img src={
user.image} />}
return {
img style={
{
width: user.imageSize,height: user.imagesize}} />
conditional rendering
- Use regular JavaScript code
<div>{
isShow? (<Component1/>) : (<Component2/>)}</div>
<div>{
isShow&& <Component/>}</div>
render list
export default function ShopList() {
const listItem = list.map(it => <li key={
it.id}>{
it.name}</li>)
return (<ul>{
listItem}</ul>)
}
li has key attribute
response event
# 组件
funciton BtnClick() {
function handleClick() {
alert('1')}
return (<button onClick={
handleClick}>click me</button>)
}
#使用
export default function myApp() {
return (<BtnClick/>)
}
update interface
- Import useState from React
import {
useState} from 'react'
function myBtn() {
const [count, setCount] = useState(0)
}
Naming convention: [something, setSomething]
Render the same component multiple times, each with child state
use hooks
- A function starting with
use
is called a Hook - useState is React's built-in Hook.
- Hooks are stricter than ordinary functions and can only be called at the top level of the component.
Sharing data between components
- The state is passed down, using JSX braces, and the passed information is called prop
- Subcomponents receive via function parameters
#父
return {
<MyBtn count={
count} onClick={
handleClick} />}
#子
function MyBtn({
count, onCLick}) {
return (<button onClick={
onCLick})>{
count}</button>
}