React采坑专区

React采坑专区

  1. this指向问题
<button onClick={this.addList}>增加</button>

// 增加
addList() {
  console.log(this)
 //=>结果是 undefined ,而且控制台报错!!!
}

解决方法:

  • 方法一:使用bind函数改变this指向
constructor(props) {
 super(props);
 this.addList = this.addList.bind(this)
}

<button onClick={this.addList}>增加</button>

// 增加
addList() {
    console.log(this)
   //=>结果是 class 对应的实例对象
}
  • 方法二:使用箭头函数
<button onClick={this.addList}>增加</button>

// 增加
addList=()=> {
    console.log(this)
   //=>结果是 class 对应的实例对象
}
  • 方法三:箭头函数
<button onClick={() => this.handleClick(1)}>增加</button>

// 写法1:
handleClick = (index) => {
console.log(this)
console.log(index)
this.setState({
	count: this.state.count + 1
})
}

// 写法2:
handleClick(index) {
console.log(this)
console.log(index)
this.setState({
	count: this.state.count + 1
})
}
  1. 注释写法:推荐使用单行注释 {/* 内容区 */};快捷键 ctrl + /

使用区域:

render(){
	return (
		 {/*  内容区 */}
	)
}
  1. 点击label标签,自动定位光标到input输入框
<label htmlFor="pink"></label>
<input id="pink"></input>
  1. React的重要特性:单项数据流

父组件向子组件传值,数据是只读的,子组件不可以改变传递的数据;

解决方法:

  • 方法一:父组件将方法传递给子组件,然后子组件用传递的方法,改变父组件的数据!!!
  1. 函数式编程
    • 代码清晰
    • 方便前端自动化测试
  2. ref采坑

点击添加会自动加入一项

<button onClick={this.addList}>增加</button>

<ul ref={(ul) => { this.ul = ul }}>
	<li>内容</li>
</ul>

// 增加
addList() {
  console.log(this)
  this.setState({
      list: [...this.state.list, this.state.inputValue],
      inputValue: ''
  })
  console.log(this.ul.querySelectorAll('li').length)
}

//=>结果:打印的结果总是比实际情况少一个;原因:this.setState是异步加载的

解决方法:将代码放在 this.setState的回调函数中

// 增加
addList() {
  console.log(this)
  this.setState({
      list: [...this.state.list, this.state.inputValue],
      inputValue: ''
  },()=>{
  	console.log(this.ul.querySelectorAll('li').length)
  })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落花流雨

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值