ReactJS:如何访问子组件的引用?

 开开2502936987 发布于 2023-01-08 11:50

我正在编写CoffeeScript中的代码,因为我一直在用它编写React.
这是基本结构.

{ div, input } = React.DOM

Outer = React.createClass
  render: ->
    div { id: 'myApp' },
      Inner()

Inner = React.createClass
  render: ->
    input { id: 'myInput', ref: 'myInput' }

toggle我的外类上有一个方法,可以通过按快捷方式触发.它切换了我的应用程序的可见性.
当我的应用程序从隐藏切换到显示时,我想专注于输入.

现在切换方法看起来或多或少像这样:

Outer = React.createClass
  render: ->
     ......

  hide: ->
    @setState { visible: no }

  show: ->
    @setState { visible: yes }

    $('#myInput').focus() # jQuery
    # I want to do something like
    # @refs.myInput.getDOMNode().focus()
    # But @refs here is empty, it doesn't contain the refs in Inner

  toggle: ->
    if @state.visible
      @hide()
    else
      @show()

那怎么办?

1 个回答
  • 访问refs子进程会破坏封装,因为refs它不被视为组件API的一部分.相反,你应该公开一个Inner可以由父组件调用的函数,调用它focus可能是有意义的.

    此外,将元素集中在一起componentDidUpdate以确保渲染完成:

    { div, input } = React.DOM
    
    Outer = React.createClass
      render: ->
        div { id: 'myApp' },
          Inner({ref: 'inner'})
    
      componentDidUpdate: (prevProps, prevState) ->
        # Focus if `visible` went from false to true
        if (@state.visible && !prevState.visible)
          @refs.inner.focus()
    
      hide: ->
        @setState { visible: no }
    
      show: ->
        @setState { visible: yes }
    
      toggle: ->
        if @state.visible
          @hide()
        else
          @show()
    
    Inner = React.createClass
      focus: ->
        @refs.myInput.getDOMNode().focus()
    
      render: ->
        input { id: 'myInput', ref: 'myInput' }
    

    2023-01-08 11:52 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有