JSX是⼀种JavaScript的语法扩展,其格式⽐较像模版语⾔,但事实上完全是在JavaScript内部实现的。
JSX可以很好地描述UI,能够有效提⾼开发效率,体验JSX。
1.表达式{}的使⽤,index.js
const name = "react study";
const jsx = <div>hello, {name}</div>;
2.函数
const obj = {
fistName: "Harry",
lastName: "Potter"
};
function formatName(name) {
return name.fistName + " " + name.lastName;
}
const jsx = <div>{formatName(user)}</div>;
- 对象
const greet = <div>good</div>;
const jsx = <div>{greet}</div>;
4.条件判断
const show = true;//false;
const greet = <div>good</div>;
const jsx = (
<div>
{/* 条件语句 */}
{show ? greet : "登录"}
{show && greet}
</div>
);
5.数据循环
const a = [0, 1, 2];
const jsx = (
<div>
{/* 数组 */}
<ul>
{/* diff时候,⾸先⽐较type,然后是key,所以同级同类型元素,key值必须得 唯⼀ */}
{a.map(item => (<li>{item}</li>))}
</ul>
</div>
);
- 属性绑定
import logo from "./logo.svg";
const jsx = (
<div>
{/* 属性:静态值⽤双引号,动态值⽤花括号;class、for等要特殊处理。 */} <img src={logo} style={{ width: 100 }} className="img" />
</div>
);
- 事件绑定
// 小驼峰写法,事件名用{}包裹
<button onClick={}>事件</button>
由于react的this指向问题,绑定事件需要特别注意,否则会出bug
一般使用的事件绑定写法有3种:
- 利用bind,用的比较少
constructor(props) {
super(props);
this.showTitleFun = this.showTitleFun.bind(this)
}
showTitleFun(){
//执行某些操作
}
//在dom元素上使用
<button onClick={this.showTitleFun}>事件</button>
- 箭头函数写法
const showTitleFun = ()=>{
//执行某些操作
}
//在dom元素上使用
<button onClick={this.showTitleFun}>事件</button>
- 直接使用箭头函数返回一个函数
showTitleFun(){
//执行某些操作
}
//在dom元素上使用
<button onClick={()=>this.showTitleFun()}>事件</button>
8.样式编写
- 行内样式编写
<img style={{height:'100px'}} />
- 添加类名
<img className="img" />
- 添加属性
<img src={logo} />
- css模块化
//创建index.module.css,index.js
import style from "./index.module.css";
<img className={style.logo} />
// 或者npm install sass -D
import style from "./index.module.scss";
<img className={style.logo} />
9.双向数据绑定
state = {
inputVal:'hahahha'
}
inputValChange = (e)=>{
this.setState({
inputVal:e.target.value
})
}
<input type='text'
value={this.state.inputVal}
onChange={ e =>{this.inputValChange(e)}}
/>