React中ref的使用

React中Ref是什么?
ref是React提供的用来操纵React组件实例或者DOM元素的接口。
ref的作用对象
ref可以作用于:

React组件的实例

class AutoFocusTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();
  }

  componentDidMount() {
    this.textInput.current.focusTextInput();
  }

  render() {
    return (
      <CustomTextInput ref={this.textInput} />
    );
  }
}

Dom元素

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

作用于React组件
React组件有两种定义方式:

function

对于用function定义的组件是没有办法用ref获取的,原因是: ref回调函数会在组件被挂载之后将组件实例传递给函数。但是使用function定义的函数并没有实例。
但是仍然可以获取function定义的组件中的DOM元素,下面会讲

class

用class定义的组件由于可以获取组件实例,因此ref函数会在组件挂载的时候将实例传递给组件

将ref回调函数作用于某一个React组件,此时回调函数会在当前组件被实例化并挂载到页面上才会被调用。
ref回调函数被调用时,会将当前组件的实例作为参数传递给函数。
Parent Component 如何获取Child component中DOM元素?
首先,能够使用ref的child Component必然是一个类,如果要实现,必然要破坏child component的封装性,直接到child component中获取其中DOM。
React16之前的获取方式
破坏封装性的获取方式

定义一个ref回调函数
并将该函数绑定Parent Component的this
将该回调函数传递给子组件
子组件中将该函数赋给需要获取的DOM元素的ref

class App extends Component {
  constructor(props) {
    super(props);
    this.getDOM = this.getDOM.bind(this);
  }

  getDOM(element) {
    this.div = element
  }

  render() {
    return (
      <div>
        <Button getDOM={this.getDOM} />
      </div>
    );
  }
}
//Button.js
export default (props) => (
  <div>
    <button ref={props.getDOM} onClick={props.onClick}>this is a button</button>
  </div>
)

不破坏封装性的获取方式

父组件定义一个ref函数,将ref赋值给Child component
Child Component中用ref获取到需要的DOM元素
Child Component中定义一个getElement的方法,然后将该DOM元素返回
父组件通过获取Child component再调用getElement即可

//APP.js

class App extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.div = React.createRef()
  }

  render() {
    return (
      <div>
        <Button ref={this.div}/>
      </div>
    );
  }
}

//Button.js

import React, {Component} from 'react';

export default class Button extends Component {
  constructor(props) {
    super(props);
    this.button = React.createRef();
    this.getButton = this.getButton.bind(this);
  }

  getButton() {
    return this.button
  }

  render() {
    return (
      <div>
        <button ref={this.button}>this is a button</button>
      </div>
    );
  }
}

React16之后的用Forwarding Refs
Forwarding Refs,React.forwardRef类似一个HOC,参数是一个function,这个function包含两个参数props和ref,返回Component,可以将这个ref用于任何子组件或者DOM

class App extends Component {
  constructor(props) {
    super(props);
    this.div = React.createRef();
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
   ***
  }

  render() {
    return (
      <div>
        <Button ref={this.div} onClick={this.handleClick}/>
      </div>
    );
  }
}

const Button = React.forwardRef((props,ref)=><button 
ref={ref}
>this is a button</button>)
// 此时父组件中的this.div 就是Button中的button dom

注意React.forwardRef参数必须是function,而这个API通常用来解决HOC中丢失ref的问题。
使用ref回调函数的注意点
我们使用ref的时候,正常理解是,ref的回调函数在组件被mount的时候调用一次,将组件的ref赋值个Parent Component的某一个属性,自此之后再不会被重新调用,除非赋了ref的组件被移除。
但是如果使用inline function 作为ref回调函数:

每当数据state、props发生变化
render 函数执行,ref inline function就要被重新创建一次,Child Component的ref属性发生了改变
React就会将Parent Component的属性值清空,然后再重新赋值
所以inline ref函数就会在每次一render时重新被调用两次

所以尽量避免使用inline function作为Component props

实例2

TodoItem.js

import React, { Component }  from 'react';
import PropTypes from 'prop-types'

class TodoItem extends Component {
	
	constructor(props){
		super(props)
		this.handleClick = this.handleClick.bind(this)
	}

	render(){
		const { content } = this.props
		return (
			<div onClick={this.handleClick}>
				{content}
			</div>
		)

	}

	handleClick(){
		const { deleteItem , index } = this.props
		deleteItem(index)
	}
}

TodoItem.propTypes = {
	content:PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
	deleteItem:PropTypes.func,
	index:PropTypes.number
}

TodoItem.defaultProps = {
	content:'hello world'
}

export default TodoItem

TodoList.js

import React, { Component, Fragment } from 'react';
import TodoItem  from './TodoItem'
import './style.css'

class TodoList extends Component {
	constructor (props){
		super(props);
		this.state = {
			inputValue : 'ddd',
			list: []
		}
		this.handleInputChange = this.handleInputChange.bind(this)
		this.handleBtnClick = this.handleBtnClick.bind(this)
		this.handleItemDelete = this.handleItemDelete.bind(this)

	}

	render() {
		return (
			<Fragment>
				<div>
					<label htmlFor='insertArea'>输入内容</label>
					<input 
					id='insertArea'
					className='input'
					value={this.state.inputValue}
					onChange={this.handleInputChange}
					ref={(input) => {this.input = input}}
					/> 
					<button onClick={this.handleBtnClick}>提交</button>
				</div>
				<ul ref={(ul) => {this.ul = ul}}>
					{ this.getTodoItem() }
				</ul>
			</Fragment>
		)
	}

	getTodoItem(){

		return this.state.list.map((item,index) => {
			return (
				<TodoItem 
				key={index}
				content={item} 
				index={index} 
				deleteItem={this.handleItemDelete}
				/>
				)
			})
	}

	handleInputChange(){
		const value = this.input.value
		this.setState(() => ({
			inputValue:value
		}))
	}

	handleBtnClick(){
		this.setState((prevState) => ({
			list:[...prevState.list,prevState.inputValue],
			inputValue:''
		}),() => {
			console.log(this.ul.querySelectorAll('div').length);
		})

	}

	handleItemDelete(index){
		this.setState((prevState) => {
			const list = [...prevState.list];
			list.splice(index,1)
			return {list}
		})
	}
}

export default TodoList;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值