gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:06:47 25 4
gpt4 key购买 nike

我正在用 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()

那我该怎么做呢?

最佳答案

访问子组件的 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' }

关于coffeescript - ReactJS:如何访问子组件的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24339706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com