关于前端:React-学习笔记

7次阅读

共计 1422 个字符,预计需要花费 4 分钟才能阅读完成。

1. JSX 与模板语法

创立一个 React 我的项目:

在 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'))

2. React 创立组件的两种形式

2.1 函数组件

实质上是一个函数

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

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'))

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'))

正文完
 0