【发布时间】:2018-05-24 05:08:15
【问题描述】:
拥有一个容器组件来保存状态。它渲染了许多无状态的组件。
我想访问他们所有的 DOM 节点,所以我可以按需调用focus method。
我正在尝试ref 方法,因为它是encouraged by the react documentation。
我收到以下错误:
Warning: Stateless function components cannot be given refs. Attempts to access this ref will fail.
解决此错误的推荐方法是什么? 最好不要使用额外的 dom 元素包装器,例如 exra div。 这是我当前的代码:
容器组件 - 负责渲染无状态组件。
import React, { Component } from 'react';
import StatelessComponent from './components/stateless-component.jsx'
class Container extends Component {
constructor() {
super()
this.focusOnFirst = this.focusOnFirst.bind(this)
this.state = {
words: [
'hello',
'goodbye',
'see ya'
]
}
}
focusOnFirst() {
this.node1.focus()
}
render() {
return (
<div>
{
this.state.words.map((word,index)=>{
return <StatelessComponent
value={word}
ref={node => this[`node${index}`] = node}/>
})
}
<button onClick={this.focusOnFirst}>Focus on First Stateless Component</button>
</div>
)
}
}
无状态组件 - 为简单起见,只需在 div 中显示文本即可。
import React from 'react';
export default function StatelessComponent(props) {
return <div>props.value</div>
}
【问题讨论】:
标签: javascript reactjs dom