react提供了creatRef
方法来帮助我们获取DOM
,下面代码通过creatRef
来获取DOM
import React, { Component, createRef } from 'react'
import ReactDom from 'react-dom'
class TestRef extends Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
todoList: []
}
// 方法的创建
this.dom = createRef();
}
handleChange= (e)=> {
this.setState({
inputValue: e.target.value
})
}
handleClick= () => {
console.log(this.dom)
this.setState(
{
todoList: this.state.todoList.concat(this.state.inputValue),
inputValue: ''
}
)
}
render() {
return (
<div>
<input value={this.state.inputValue} onChange={this.handleChange}></input>
{/***
* 在button标签中使用ref = {this.dom},在其他地方使用时,this.dom就是获取到的button了
*/}
<button ref={this.dom} onClick={this.handleClick}>添加</button>
{this.state.todoList.map((x, index) => {
return (
<h1 key ={index}>{x}</h1>
)
})}
</div>
)
}
}
export default TestRef;