使用场景
- 父组件操作子组件input标签时的简单方法
- forwordRef 只能是一个input不适合多个
forwordRef 方法
import React, { Component } from 'react'
import { forwardRef } from 'react'
export default class App extends Component {
myref = React.createRef()
render() {
return (
<div>
<Child ref={this.myref}></Child>
<button onClick={() => {
console.log(this.myref, this.myref.current.value)
this.myref.current.value = ''
this.myref.current.focus()
}}>click</button>
</div>
)
}
}
const Child = forwardRef( (props, ref) => {
return(
<>
<input ref={ref} defaultValue='kkk'/>
</>
)
})
传统方法
import React, { Component } from 'react'
export default class App extends Component {
myref = null
render() {
return (
<div>
<Child callback= {(myref) => {
this.myref = myref
}}></Child>
<button onClick={() => {
console.log(this.myref, this.myref.current.value)
this.myref.current.value = ''
this.myref.current.focus()
}}>click</button>
</div>
)
}
}
class Child extends Component {
myref = React.createRef()
componentDidMount() {
this.props.callback(this.myref)
}
render() {
return <>
<input defaultValue={'hhhh'} ref={this.myref} />
</>
}
}