第二十八章:forwordRef

使用场景

  • 父组件操作子组件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} />
    </>
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容