EventBind.jsx
import React, { Component } from 'react'
import ReactDOM from 'react-dom';
export default class EventBind extends Component {
/**
*
* 该组件主要介绍:
* 事件绑定
* 操作dom
* setState() 的参数
*/
constructor(props) {
super(props);
this.handleClick3 = this.handleClick3.bind(this)
}
state = {
msg: '改造后的react',
list: ['vue', 'react', 'flutter'],
isShow: true
}
handleEmptyTag() {
return (
<>
<td>vue</td>
<td>react</td>
<td>flutter</td>
</>
)
}
handleClick2() {
console.log(this)
}
handleClick3() {
console.log(this)
}
handleClick4 = () => {
console.log(this)
}
handleClick5 = () => {
/*
setState函数有两个参数:
第一个参数:
可以是对象,就是正常修改值就可以
如果是函数,必须写成以下格式:
多行写法:
(state, props) => {
return {
isShow: !this.state.isShow
}
}
单行写法:
(state) => ({
isShow: !this.state.isShow
})
也可以接受组件传值
*/
// this.setState({
// isShow: !this.state.isShow
// }, () => {
// console.log(this.state.isShow)
// })
this.setState((state, props) => {
// 此时父组件没有传值,所以打印出{}
console.log(props) // {}
return { isShow: !this.state.isShow }
}, () => {
console.log(this.state.isShow)
})
console.log(this.state.isShow)
}
/**
操作dom的5种方式:
注意:避免过多的操作dom元素
*/
handleDom1 = () => {
const oTitle = document.querySelector('#title1')
console.log(oTitle)
oTitle.style.background = "red"
}
handleDom2 = () => {
console.log(this)
const { title2 } = this.refs
title2.style.background = "green"
}
handleDom3 = () => {
const oTitle = document.querySelector('#title3')
// 要使用ReactDOM必须要引入
ReactDOM.findDOMNode(oTitle).style.background = "yellow"
}
handleDom4 = () => {
console.log(this._h1Ele)
this._h1Ele.style.background = "hotpink"
}
render(){
return (
<div>
<h1>{this.state.msg}</h1>
<ul>
{
this.state.list.map((item, index) => {
return <li key={index}>{item}</li>
})
}
</ul>
<table>
<tbody>
<tr>
{this.handleEmptyTag()}
</tr>
</tbody>
</table>
{/* 6种事件绑定: 前两种就不做介绍了 */}
<p>
<button onClick={this.handleClick2.bind(this)}>事件2 可以传参</button>
</p>
<p>
<button onClick={this.handleClick3}>事件3 不能传参</button>
</p>
<p>
<button onClick={this.handleClick4}>事件4</button>
</p>
<p>
<button onClick={this.handleClick5}>事件5 {this.state.isShow ? 'ON' : 'OFF'}</button>
</p>
{/* 5种操作DOM的方式: */}
<h1 id='title1'>Dom操作 1</h1>
<p>
<button onClick={this.handleDom1}>handle dom 1</button>
</p>
<h1 ref="title2">Dom操作 2</h1>
<p>
<button onClick={this.handleDom2}>handle dom 2</button>
</p>
<h1 id="title3">Dom操作 3</h1>
<p>
<button onClick={this.handleDom3}>handle dom 3</button>
</p>
{/* 新版本react推荐使用callback这种方式 */}
<h1 ref={ele => this._h1Ele = ele}>Dom操作 4</h1>
<p>
<button onClick={this.handleDom4}>handle dom 4</button>
</p>
</div>
)
}
}