react中refs的使用方法
react中refs的使用
1、在dom元素中直接使用ref
意思就是可以在组件中创建一个dom节点的textInput,并将ref直接绑定到他
2、为class组件添加refs 这个时候 refs指向的是子组件的实例 这样在父组件中可以调用子组件中的方法
当为了使用更方便时可以直接在子组件上定义一个refs别名 作为props传递个子组件
在父组件中想获取子组件的哪个dom元素 就将刚刚传递个子组件的props 作为dom元素ref属性的值
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import { ThemeContext,themes } from './components/ThemeContext';
import ThemeButton from './components/ThemeButton'
class CustomInput extends React.Component{
constructor(props){
super(props)
}
render(){
return <input onChange={()=>{}} value="fouse" ref={this.props.inputRef} />
}
}
class App extends React.Component{
constructor(props){
super(props)
this.input = React.createRef()
}
componentDidMount() {
this.input.current.focus()
}
render(){
return (
)
}
}
ReactDOM.render(
3、通过转发的方式将将 DOM Refs 暴露给父组件
4、回调refs
注:内联的回调refs 会调用二次 第一次返回null
内联的写法:
1
<input ref={(e)=>this.inputText=el} onChange={()=>{}} value="inputfocus" />

浙公网安备 33010602011771号