react三种定义ref的方式

在react中要想获取节点,得借助ref来实现,
第一种直接定义字符串

	<input
	type="text"
	placeholder="失去焦点提示数据"
	ref="input2"
	onBlur={
    
    this.demo1}
	/>				
	//然后在实例上的refs里面调用
		demo1 = () => {
    
    //操作节点
					console.log(this.refs.input2.value)
				}		

第二种使用回调函数

  <input
	type="text"
	onKeyDown={
    
    this.demo}
	ref={
    
    currentNode => {
    
    // 使用回调函数,在实例上让input为该节点
	this.input = currentNode//注意当页面更新的适合该回调函数执行两次                                
	}}    />
	
							

第三种定义容器来接收节点

 myRef = React.createRef()//该容器只接受一个节点,返回一个对象
 <h1 ref={
    
    this.myRef}>Hello World</h1>

猜你喜欢

转载自blog.csdn.net/qq_46433453/article/details/123487526