react learning 01-quick start

Quick Start – React (docschina.org)

React components must start with a capital letter, while HTML tags must be lowercase.

Write tags using JSX

  1. JSX is stricter than HTML. must close tag
  2. Cannot return multiple JSX tags, they must be wrapped in a shared parent (a root element)
  3. If you have a lot of HTML that needs to be ported to JSX, you can use an online converter .

add style

  1. Use classNamespecified
<img className="avatar" />

Display Data

  1. brace wrap
  2. 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

  1. 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

  1. 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

  1. A function starting with useis called a Hook
  2. useState is React's built-in Hook.
  3. Hooks are stricter than ordinary functions and can only be called at the top level of the component.

Sharing data between components

  1. The state is passed down, using JSX braces, and the passed information is called prop
  2. Subcomponents receive via function parameters
#父
return {
    
    <MyBtn count={
    
    count} onClick={
    
    handleClick} />}
#子
function MyBtn({
     
     count, onCLick}) {
    
    
    return (<button onClick={
    
    onCLick})>{
    
    count}</button>
}

Guess you like

Origin blog.csdn.net/weixin_46211267/article/details/132208163