react 基础

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>;
  1. 对象
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>
);
  1. 属性绑定
import logo from "./logo.svg";
const jsx = (
<div>
 {/* 属性:静态值⽤双引号,动态值⽤花括号;class、for等要特殊处理。 */} <img src={logo} style={{ width: 100 }} className="img" />
</div>
);
  1. 事件绑定
// 小驼峰写法,事件名用{}包裹
<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)}}

/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值