2、jsx核心语法
2.1 class
和java很像啊
<script>
// 定义一个对象
class Person {
//构造函数
constructor(name , age){
this.name = name;
this.age = age;
}
// 定义一个方法
sayHello(){
console.log(`hello ${this.name}`);
}
}
// 创建一个对象
Person1 = new Person('张三' , 18);
// 调用对象的方法
Person1.sayHello();
// 继承:提高代码复用性
class Student extends Person{
// 构造函数
constructor(name , age , score){
// 调用父类的构造函数
super(name , age);
this.score = score;
}
// 重写父类的方法
sayHello(){
// 调用父类的方法
super.sayHello();
console.log(`我的分数是${this.score}`);
}
}
// 创建一个对象
Student1 = new Student('李四' , 20 , 100);
// 调用对象的方法
Student1.sayHello();
</script>
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 嵌入表达式
<h2>{firstname + lastname}</h2>
<h2>{5 * 3}</h2>
<h2>{isLogin ? "成功登录" : "登录失败"}</h2>
<h2>{this.getFullName()}</h2>
2.3 绑定
2.3.1 绑定属性
主要就是两个class和style
{/*绑定class , className*/}
<div className="title">我是className</div>
{/*绑定style , 小驼峰*/}
<div style={{
color: "red",
fontSize: "20px",
backgroundColor: "yellow",
padding: "10px"
}
}>绑定style</div>
2.3.2 绑定事件
绑定事件就是onClick,但是一定要注意this的执行
<script type="text/babel">
class App extends React.Component {
constructor() {
super()
this.state = {
message:"我是h2",
num:0
}
// 初始化的时候就绑定this
this.increaseNum = this.increaseNum.bind(this)
}
render() {
return (
<div>
<h2 onClick={this.btnClick.bind(this)}>点击我</h2>
<h3 onClick={this.increaseNum}>加1</h3>
<h2 onClick={this.showNum}>展示数字</h2>
</div>
)
}
btnClick() {
console.log(this.state.message)
}
increaseNum() {
console.log(this.state.num + 1)
}
showNum = () => {
console.log(this.state.num)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
</script>
在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是通过条件判断来决定是否渲染该元素。
<h4 style={{ display: isLogin ? "block" : "none" }}> 欢迎公主回家 </h4>
2.4.2 列表渲染
使用map高阶函数
<ul> <h2>数组展示</h2> { this.state.foods.map((item , index , arr) => { return ( <li key={index}> {item} </li> ) }) } </ul>
filter:进行过滤
<ul> <h2>数组筛选</h2> { this.state.num.filter((item , index , arr) => { if( item % 2 === 0) { return true } else { return false } }).map((item , index , arr)=> { return ( <li key={index}> {item} </li> ) }) } </ul>
slice:进行截取
<ul> <h2>数组截取</h2> { this.state.foods.slice(0,3).map((item , index , arr) => { return ( <li> {item} </li> ) }) } </ul>