React---day2

2、jsx核心语法

2.1 class

和java很像啊

   

2.2 嵌入数据

2.2.1 嵌入变量

在{}中可以正常显示的内容:

                    name:"jyx" , //String
                    age: 20 , //Number
                    names:["axigg" , "abc"],//Array

在{}中不能正常显示的内容(忽略)

                    text1:null,//null
                    text2:undefined,//undefied
                    test3:false,//boolean

为什么???就是避免出现undefied显示在页面上的情况

2.2.2 嵌入表达式
              

{firstname + lastname}

{5 * 3}

{isLogin ? "成功登录" : "登录失败"}

{this.getFullName()}

2.3 绑定

2.3.1 绑定属性

主要就是两个class和style

 {/*绑定class , className*/}
              
我是className
{/*绑定style , 小驼峰*/}
绑定style
2.3.2 绑定事件

绑定事件就是onClick,但是一定要注意this的执行

 

​ 在btnClick中打印this,结果是undefined

​ 这是因为btnClick方法没有被绑定到组件实例上,btnClick方法在被调用时,this指向了全局对象而不是组件实例,this默认为undefined。

  • 解决方法1:在构造函数中使用this.btnClick = this.btnClick.bind(this) — 显式绑定,不常见
  • 解决方法2: 给btn函数在初始化的时候就绑定this
  • 解决方法3:使用箭头函数,箭头函数不会创建自己的this,它会捕获上下文中的this值

2.4 渲染

2.4.1 条件渲染
  • 在JSX中可以使用三元运算符来进行条件渲染。

例如:{isLogin ?

欢迎回来

:

请先登录

}

  • 也可以使用逻辑与运算符(&&)来简化条件渲染。

    例如:{isLogin &&

    你好啊,蒋乙菥

    }

  • v-show是通过设置元素的style属性来控制显示和隐藏,而v-if是通过条件判断来决定是否渲染该元素。

     

    欢迎公主回家

2.4.2 列表渲染
  • 使用map高阶函数

  •    

      数组展示

      { this.state.foods.map((item , index , arr) => { return (
    • {item}
    • ) }) }
  • filter:进行过滤

  •  

      数组筛选

      { this.state.num.filter((item , index , arr) => { if( item % 2 === 0) { return true } else { return false } }).map((item , index , arr)=> { return (
    • {item}
    • ) }) }
  • slice:进行截取

  •     

      数组截取

      { this.state.foods.slice(0,3).map((item , index , arr) => { return (
    • {item}
    • ) }) }

你可能感兴趣的:(react学习,react.js,javascript,前端)