1. JSX 与模板语法

创建一个 React 项目:
image.png

在 React 中实现循环遍历

import React from 'react'
import ReactDOM from 'react-dom'
// JSX == JavaScript + xml
// 循环绑定 使用 map
const arr = [1, 2, 3]
// DOM 对象
const ulEle = arr.map((item, index) => <li key={index}>{item}</li>)
// ReactDOM.render(DOMObj, document.querySelector('#root'))
ReactDOM.render(<ul>{ulEle}</ul>, document.querySelector('#root'))

image.png

2. React 创建组件的两种方式

2.1 函数组件

本质上是一个函数

// props 携带参数
function Welcome(props) {
  return <h2>hello,{props.name}</h2>
}
ReactDOM.render(<Welcome name="lsy" />, document.querySelector('#root'))

image.png

2.2 类组件

// 1.必须继承 React.Component
class App extends React.Component {
// 2.必须有 render 函数
  render() {
// 3.一定要返回 DOM 元素
    return <h2>App,{this.props.name}</h2>
  }
}
ReactDOM.render(<App name="lsy" />, document.querySelector('#root'))

image.png

3. React 组件拆分

创建一个公共组件:

// App.js
import React, { Component } from 'react'

// App => MyBtn
class MyBtn extends Component {
  render() {
    return <button>{this.props.title}</button>
  }
}

class App extends Component {
  constructor(props) {
    super(props)
    // 遵循单向数据流
    this.user = {
      name: '李诗瑶',
      content: '这是我的react组件',
      date: new Date().toLocaleDateString()
    }
  }
  render() {
    return (
      <div>
        <h2>hello,{this.props.name}</h2>
        <MyBtn title="提交"></MyBtn>
        <div className="comment">
          {/* 用户信息 */}
          <div className="userinfo">name:{this.user.name}</div>
          {/* 内容 */}
          <div>common:{this.user.content}</div>
          {/* 时间 */}
          <div>date:{this.user.date}</div>
        </div>
      </div>
    )
  }
}

export default App

调用 App 组件

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(<App name="yoyo"></App>, document.querySelector('#root'))

image.png

4. 子传父

在父组件中定义改变数据的方法并传递给子组件,在子组件中访问改方法来修改父组件数据,要注意 this 指向。

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
// 子组件
class ChildCom extends Component {
  constructor(props) {
    super(props)
    this.state = {
      val: ''
    }
    this.handlerClick = this.handlerClick.bind(this)
    this.handlerChange = this.handlerChange.bind(this)
  }
  handlerChange(event) {
    this.setState({
      val: event.target.value
    })
  }
  handlerClick() {
    if (this.state.val) {
      // 调用父组件的方法
      this.props.addHandler(this.state.val)
      // 清空输入框
      this.setState({
        val: ''
      })
    }
  }
  render() {
    return (
      <div>
        <input type="text" value={this.state.val} onChange={this.handlerChange} />
        <button onClick={this.handlerClick}>添加</button>
        {this.props.menus.map((item, index) => {
          return <p key={index}>{item}</p>
        })}
      </div>
    )
  }
}
// 父组件
class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      menus: ['烤腰子', '辣炒鸡丁', '炸黄花鱼']
    }
  }
  // 一定要使用箭头函数
  addHandler = (val) => {
    this.state.menus.push(val)
    // 更新视图=>render
    this.setState({
      menus: this.state.menus
    })
  }

  render() {
    // 修改状态之后,会重新调用render
    return (
      <div>
        <ChildCom menus={this.state.menus} addHandler={this.addHandler}></ChildCom>
      </div>
    )
  }
}
ReactDOM.render(<App />, document.querySelector('#root'))

5. Hook 组件

Hook 类似 Vue3 的写法

import React, { useEffect, useState } from 'react'
import { Table, Tag, Space, Button } from 'antd'

function Example1() {
  // 声明一个叫 count 的变量
  // 声明一个修改 state 的函数
  // 初始化 state
  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>
    },
    {
      title: 'Age',
      dataIndex: 'age',
      key: 'age'
    },
    {
      title: 'Address',
      dataIndex: 'address',
      key: 'address'
    },
    {
      title: 'Tags',
      key: 'tags',
      dataIndex: 'tags',
      render: (tags) => (
        <>
          {tags.map((tag) => {
            let color = tag.length > 5 ? 'geekblue' : 'green'
            if (tag === 'loser') {
              color = 'volcano'
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            )
          })}
        </>
      )
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <a>Invite {record.name}</a>
          <a>Delete</a>
        </Space>
      )
    }
  ]
  const [data, setData] = useState([])
  const getData = () => {
    setData([
      {
        key: '1',
        name: 'John Brown',
        age: 32,
        address: 'New York No. 1 Lake Park',
        tags: ['nice', 'developer']
      }
    ])
  }
  return (
    <div className="table">
      <Button onClick={getData}>点我初始化数据</Button>
      <Table columns={columns} dataSource={data}></Table>
    </div>
  )
}
function Example2() {
  const [count, setCount] = useState(0)
  // 在 update 和 mounted 时触发
  let timer = setInterval(() => setCount(count + 1), 2400)
  useEffect(() => {
    document.title = '我点击了' + count + '次'
    return () => {
      clearInterval(timer)
    }
  })
  return (
    <h1>
      {count}
      <hr />
      <Button
        onClick={() => {
          setCount(count + 1)
        }}
      >
        add
      </Button>
    </h1>
  )
}

function App() {
  return (
    <div className="App">
      <Example1 />
      <Example2 />
    </div>
  )
}
export default App

逃跑计划
8 声望1 粉丝

一个前端