学习react的语法(1)

132 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第17天,点击查看活动详情

前言

最近要在新项目使用react,因为之前是使用的vue,所以需要从0开始学习,所以通过文章记录学习的过程。

react语法

构建项目

和vue-cli一样,react也有构建工具,叫create-react-app

可以全局安装

npm install -g create-react-app
yarn global add create-react-app

通过create-react-app react-app创建名为react-app的react项目。

如果不是全局安装,可以通过npx安装。

npx create-react-app my-app

我是用的依赖版本如下,下面的语法都是基于下面的版本

    "react": "^18.1.0"
    "react-dom": "^18.1.0"

react-dom主要是提供dom的一些方法,提供了clientserver两个模块。

语法

import React from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'

const root = createRoot(document.getElementById('root'))
root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
)

通过react-domcreateRoot方法,绑定顶层的渲染元素。

然后使用render方法渲染引入的app组件。

React.StrictMode是对它包裹的组件进行严格检查,比如过时的api,或者钩子等等。不会渲染成元素,仅在开发环境时有效。

jsx语法

在react中,创建dom元素一般都是使用jsx语法,这样阅读会方便一些。

这个函数返回的就是jsx语法,通过()包裹

function App () {
  return (
    <div className="App">
      <span>hello world</span>
    </div>
  )
}

你也可以使用React.createElement()方法来创建dom元素。不过编写没有jsx那么方便。

等同于上面的jsx

React.createElement(
    'div',
    { className: 'App' },
    [
      React.createElement('span', null, 'hello world')
    ]
)

tips: jsx最终也是通过babel转成React.createElement()来创建dom元素。

推荐使用jsx语法,方便阅读。

大括号表达式

我们可以在jsx中嵌入变量,通过大括号包裹就行,其实大括号不单单只能包裹变量,任何js表达式都可以。

function App () {
  const text = ' world!'
  const style = {
    color: 'red'
  }
  return (
    <div className="App" style={style}>
      <span>{'hello' + text}</span>
    </div >
  )
}

渲染的结果:

image.png

image.png

注意jsx中类名需要使用className,避免与es6的class冲突。