欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

React (a) 认识 React,熟悉类组件、JSX 编写规范、嵌入式变量表达式、绑定属性 - 三种、JSX 语法

最编程 2024-10-14 18:22:25
...

1. 认识JSX

 // 1. 定义元素内容
 const element = <div>Hello World</div>
 // 2. 渲染
 const root = ReactDOM.createRoot(document.querySelector('#root'))
 root.render(element)

在js中,将一段html直接赋值给变量element会出现语法错误。而在jsx语法中(开启babel:type="text/babel"),第2行代码不会报错。

  • JSX是一种JavaScript的语法扩展(eXtension),也称为JavaScript XML
  • 它用于描述我们的UI界面,并且它可以和JavaScript融合在一起使用;
  • 它不同于Vue中的模块语法,不需要专门学习模块语法中的一些指令(比如v-for、v-if、v-else、v-bind);

2. JSX书写规范及注释

书写规范:
(1) JSX只能有一个根元素,一般会在外层包裹一个<div>(或者使用后边学习的Fragment)
(2) 为了方便阅读,有多行代码时,会在jsx外层包裹一个小括号
(3) JSX中的标签可以是单标签或双标签
在这里插入图片描述
注释
语法:{/*注释内容...*/}

  render () {
    return (
      <div>
        {/*JSX的注释写法*/}
        // JSX的注释写法---这样写仍旧会展示到页面上
        <h2>当前计数为:{this.state.number}</h2>
      </div>
    )
  }

在这里插入图片描述

3. JSX嵌入变量作为子元素

子元素就是标签里的内容。<h2 title='111'>aaa</h2> aaa是子元素,title是标签属性。

(1). 当变量是Number,String,Array类型时,可以直接显示

 this.state = {
   // 1. 变量是Number,String,Array类型
   number: 0,
   name: 'tom',
   movies: ['加勒比海盗', '百鸟朝凤', '飞屋环游记'],
 }
 render () {
   const { number, name, movies } = this.state
   return (
     <div>
       {/*1. 变量是Number,String,Array时,直接显示*/}
       <h2>{number}</h2>
       <h2>{name}</h2>
       <h2>{movies}</h2>
     </div>
   )
 }

在这里插入图片描述

(2). 当变量是null,undefined,Boolean类型时,不显示
  若要显示,则需要转换成字符串(比如toString方法、空字符串拼接String(变量))

   this.state = {
     // 2. 变量是null, undefined, Boolean
     aaa: null,
     bbb: undefined,
     ccc: true,
   }
  render () {
    const { aaa, bbb, ccc } = this.state
    return (
      <div>
        {/*2. 变量是null, undefined, Boolean时,内容为空*/}
        <h2>{aaa}</h2>
        <h2>{bbb}</h2>
        <h2>{ccc}</h2>
        {/*2 若要显示,则需要转换成字符串*/}
        <h2>{aaa + ''}</h2>
        <h2>{String(bbb)}</h2>
        <h2>{ccc.toString()}</h2>
      </div>
    )
  }

在这里插入图片描述

(3). Object对象类型的变量不能作为子元素,会报错

 this.state = {
   friend: {
     name: 'jerry'
   }
 }
  render () {
   const { friend } = this.state
   return (
     <div>
       <h2>{friend}</h2>
     </div>
   )
 }

在这里插入图片描述
可以写对象里具体的属性

   {/*<h2>{friend}</h2>*/}
   <h2>{friend.name}</h2>  // jerry
   <h2>{Object.keys(friend)[0]}</h2> // name

4. JSX嵌入表达式

运算表达式,三元运算符,执行函数

 this.state = {
      firstName: '张',
      lastName: '三',
      age: 20,
      movies: ["流浪地球", "星际穿越", "独行月球"]
    }
  // 渲染函数
  render () {
    const { firstName, lastName } = this.state
    const fullName = firstName + ' ' + lastName
    const { age } = this.state
    const ageText = age >= 18 ? "成年人" : "未成年人"
    return (
      <div>
        {/*1 运算表达式*/}
        <h2>{10 + 20}</h2>
        <h2>{firstName + '' + lastName}</h2>
        <h2>{fullName}</h2>

        {/*2 三元运算符*/}
        <h2>{ageText}</h2>
        <h2>{age > 18 ? '成年人' : '未成年人'}</h2>

        {/*3 执行一个函数*/}
        <ul>{this.state.movies.map(movie => <li>{movie}</li>)}</ul>
        <ul>{this.getMovieEls()}</ul>
      </div >
    )
  }
  getMovieEls () {
    const liEls = this.state.movies.map(movie => <li>{movie}</li>)
    return liEls
  }

在这里插入图片描述

5. JSX绑定属性

(1) title,src,href属性

this.state = {
  title: "哈哈哈",
  imgURL: "https://ts1.cn.mm.bing.net/th/id/R-C.95bc299c3f1f0e69b9eb1d0772b14a98?rik=W5QLhXiERW4nLQ&riu=http%3a%2f%2f20178405.s21i.faiusr.com%2f2%2fABUIABACGAAgoeLO-wUo4I3o2gEw8Qs4uAg.jpg&ehk=N7Bxe9nqM08w4evC2kK6yyC%2bxIWTjdd6HgXsQYPbMj0%3d&risl=&pid=ImgRaw&r=0",
  href: "https://www.baidu.com",
}
// 渲染函数
 render () {
   const { title, imgURL, href } = this.state
   return (
     <div>
       <h2 title={title}>h2 标题</h2>
       <img src={imgURL} />
       <a href={href}>百度链接</a>
     </div >
   )
 }

(2) 绑定class

需求:给h2绑定 abc cba, 当isActive为true时,绑定active,否则不绑。
注意:React绑定类名时,用className,而不是class(用class会有警告)

(1)方式一:拼接字符串

  this.state = {
    isActive: false
  }
  render () {
    const { isActive } = this.state
    // 1. 绑定方法一:字符串拼接
    const className = `abc cba ${ isActive ? 'active' : '' }`
     return (
      <div>
        <h2 className="abc cba">哈哈哈哈</h2>
        {/*动态绑定*/}
        <h2 className={className}>哈哈哈哈</h2>
      </div >
    )
  }

缺点是,当isAcrtve为false时,类名里会多出一个空格
在这里插入图片描述

(2) 方式二:将所有的class类名放到数组里

   render () {
     const { isActive } = this.state
     // 2. 绑定方法二:将所有的class放到数组里
     const className = ['abc', 'cba']
     // isActive为true就添加active类名
     if (isActive) className.push('active')
     return (
       <div>
         <h2 className={className.join('')}>哈哈哈哈</h2>
       </div >
     )
   }
 }

className为数组时:
类名解析出来有逗号:<h2 class="abc,cba">哈哈哈哈</h2>
所以需要.join进行处理

(3)方式三:第三方库classnames -> npm install classnames;后续再补充

(3) 绑定style样式

绑定style样式时,需要使用对象形式,属性名采用驼峰命名;
注意:JSX绑定子元素时不可以用对象,这里是绑定属性,可以用对象

  this.state = {
    objStyle: { color: "red", fontSize: "30px" }
  }
 render () {
     const {objStyle } = this.state
     return (
       <div>
         { /* 绑定style属性: 绑定对象类型,第一个{}是语法,第二个{}表示对象 */}
         <h2 style={{ color: "red", fontSize: "30px" }}>呵呵呵呵</h2>
         <h2 style={objStyle}>呵呵呵呵</h2>
       </div >
     )
   }