react基础语法学习

1、在react中用jsx语法

(1)在html中使用{}嵌套变量
const name = "我是变量";
<div>{name}</div>
(2)属性添加设置
const imgUrl = ''./imgs/box.png";
<img src={imgUrl} alt=""/>
注意:
1. for属性在jsx中替换成了htmlFor
<label htmlFor=""></label>
2. class属性在jsx中替换成了className
<div className=""></div>
3. 动态className
const active = true;
<a href="" className={ "title box" + {active?"active":""} }/>
4. 内联样式,最外层是说明里面写的是jsx代码
<div style={{ color: "red", fontSize: "20px" }}></div>
(2)注释常用语法
{/*注释写这里边*/}
(3)点击事件触发
1.es6箭头函数传递this
<div onClick={() => this.update()}/>
2. 在箭头函数内不绑定this,此时this指向上一层

点击查看代码
constructor(props) {
		super(props);
}
render() {
	return (
		<div onClick={this.btnClick}></div>
		<div onClick={this.btnClick}></div>
	)
}
btnClick = () => {
	//this指向提前在构造器内已经做过绑定
	console.log(this);
}
3. 需要特别注意下面这种写法,this指向问题,需要改变this指向,此时的this是从render函数内传递到了update函数内,此方法实际开发中不常用 `
`

(4)构造器内写data数据,类似于vue里面的data返回数据的函数

点击查看代码
constructor(props) {
	//但凡涉及到继承关系,需要使用父类的某些方法或属性,
	//就需要使用super去初始化父类里面的方法和属性,通过super传递属性值,将this指回本身
		super(props);
		//数据存放处
		this.state = {
		  visible: false,
		  title: ''标题",
		  list: [''111", 2223],
		}
}

(5)注意:react语法中null,undefined,布尔,Object等类型均不会在页面显示

点击查看代码
export default class Modal extends Component {
	 constructor(props) {
		super(props);
		this.state = {
		  test1: false,
		  test2: true,
		  test3: null,
		  test4:  undefined,
		  visible: false,
		  title: ''标题",
		  list: [''111", 2223],
		}
	  }
	  render() {
	  	const { title, visible, list } = this.state;
		return (<div>
		{/*页面展示*/}
			<h1>{title}</h1>
		{/*页面展示*/}
			<h1>{list}</h1>
		{/*页面不展示*/}
			<h1>{test1}</h1>
		{/*页面不展示*/}
			<h1>{test2}</h1>
		{/*页面不展示*/}
			<h1>{test3}</h1>
		{/*页面不展示*/}
			<h1>{test4}</h1>
		</div>)
	}
}

(6)动态修改state内存储的数据

点击查看代码
export default class Modal extends Component {
	 constructor(props) {
		super(props);
		this.state = {
		  visible: false,
		  title: ''标题",
		  list: [''111", 2223],
		}
	  }
	  update = (bool) => {
	  	this.state = ({
		 visible: bool,
		})
	  }
	  render() {
	  	const { title, visible, list } = this.state;
		return (<div>
			<h1>{visible?title:null}</h1>
			<h1 onClick={() => this.update(true)}>{list}</h1>
		</div>)
	}
}

posted @ 2022-06-29 11:50  ~柚子~  阅读(60)  评论(0)    收藏  举报