react ref的使用

react虚拟dom如何通过ref来获取呢,看如下代码:

import React, {Component, Fragment} from 'react';
import TodoItem from './TodoItem';
class TodoList extends Component {
constructor (props)
{
super (props);
this.state = {
inputValue: 'hello',
list: []
}
}

render ()
{
return (<Fragment>
<div><input
value={this.state.inputValue}
onChange={
e => this.handleInput (e)}
ref={(input) =>{this.input = input}} //ref这里是一个函数通过这种方式获取相应的input标签
/>
<button onClick={
e => this.handleClick ()}>提交
</button>
</div>
<ul ref={(ul) =>{this.ul = ul}}>{this.state.list.map ((item,
index) => {
return (<TodoItem item = {item}
index={index}
key={index}
deleteItem = {() =>this.cancel()
}
/>)
})}
</ul>

</Fragment>)
}

handleInput (e)
{
this.setState ({
inputValue: this.input.value //以前获取input的value值是通过e.target.value来获取这里通过ref获取了相应的dom节点就可以这样写了
})
}

handleClick ()
{
let list = [];
list.push (this.state.inputValue);
this.setState ({
list: [...this.state.list,this.state.inputValue],
inputValue:''
},() =>{
console.log(this.ul.querySelectorAll('div').length) //
this.setState 是异步函数,它还接收第二个参数,相当于回调函数,只不过这个参数是函数获取新生成的div的长度可以放在这个函数中执行相应的
代码,setState是异步的获取dom不及时总会少于1,通过在其回调函数中获取相应的dom

})
}
cancel(index) {
const list = [...this.state.list];
list.splice(index,1);
this.setState({
list:list
})
}
}

export default TodoList
 
 
原文地址:https://www.cnblogs.com/zhx119/p/11023624.html