ReactJS:如何访问子组件的引用? [英] ReactJS: How to access refs of child component?
问题描述
我在CoffeeScript中编写代码,因为我一直在用它编写React。
这是基本结构。
I'm writing the code in CoffeeScript since I've been writing React with it.
Here is the basic structure.
{ div, input } = React.DOM
Outer = React.createClass
render: ->
div { id: 'myApp' },
Inner()
Inner = React.createClass
render: ->
input { id: 'myInput', ref: 'myInput' }
toggle
方法在我的外部类,通过按快捷方式触发。它切换我的应用程序的可见性。
当我的应用程序从隐藏切换到显示时,我想关注输入。
I have a toggle
method on my Outer class which is triggered by pressing a shortcut. It toggles the visibility of my app.
When my app is toggled from hidden to shown, I want to focus on the input.
现在切换方法看起来或多或少像这样:
Now the toggle methods look more or less like this:
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
不被视为组件的API的一部分。相反,你应该在 Inner
上暴露一个可以由父组件调用的函数,调用 focus
可能有意义。
Accessing the refs
of a child breaks encapsulation since refs
are not considered part of a component's API. Instead you should expose a function on Inner
that can be called by a parent component, calling it focus
might make sense.
此外,将元素的焦点放在 componentDidUpdate
中以确保渲染完成:
Also, focus the element in componentDidUpdate
to ensure rendering is complete:
{ 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' }
这篇关于ReactJS:如何访问子组件的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!