我正在尝试将我在array.map上呈现的组件赋予引用,以便稍后我可以调用这些组件中的一些函数。
同一个组件会有3个实例,给他们一个参考时我会收到这个错误:
Uncaught Error: Stateless function components cannot have refs.
这里是尝试渲染这3个子组件的父组件的render方法:
render() {
const { strings } = this.props;
const ElementsContainer = ({elements}) => (
<div className="containerSection">
{elements.map( (element, i) => {
return(<div key={"container"+i} className="camaraLentaContainer" id={"camaraLentaContainer" + i}>
<CamaraLenta ref={"camaraLenta"+i} index={i} images={element.camaraLenta.images}/>
</div>)
})
}
</div>
)
return (
<div className="home" >
<ElementsContainer elements={strings.elements} />
</div>
);
}
这里,CamaraLenta(子)组件非常简化,所以我们可以看到..
import ...;
export default class CamaraLenta extends React.Component {
static propTypes = {
name: PropTypes.string,
};
static contextTypes = {
baseUrl: PropTypes.string.isRequired,
project: PropTypes.string.isRequired
}
constructor(props) {
super(props);
this.state = {
slideIndex: 0,
loading: false,
imagesTotalDataSrc: [],
imagesTotalDataLoaded: 0,
timeoutSlider: null
};
this.handleSliderClick = this.handleSliderClick.bind(this);
}
componentDidMount() {
}
//Touch/Click slider, we kill timeout
handleSliderClick() {
clearTimeout(this.state.timeoutSlider);
}
registerEvents(){
$("html, body").on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
$("html, body").stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
});
}
render() {
const {index} = this.props;
return (
<div>
<div className="slidesContainer">
<canvas id={"stage" + index}>
Tu navegador no soporta canvas
</canvas>
<div className="slider" id={"slider" + index} onClick={this.handleSliderClick}></div>
<Loading visible={this.state.loading}/>
</div>
</div>
);
}
}`
我的版本:
"react": "^15.5.4",
"react-redux": "^5.0.5",
"redux": "^3.7.0",
答案 0 :(得分:1)
无状态组件不适用于refs,如果你真的想使用findDOMNode解封组件,将你的组件转换为基于类的组件,或者在0.14之前将你的反应降级到任何版本(不推荐)。
此页面中的更多信息,讨论了他们为何从无状态组件中删除此功能https://github.com/facebook/react/issues/4936
答案 1 :(得分:1)
好的。有些人在答案上提出建议,我弄错了。无状态组件/函数是ElementsContainer,我在渲染函数中声明了它。
最后,我改变了我对此的引用方式:
ref={ el => this.camerasRefs.push(el) }
并且,在我的主要组件构造函数中,我声明了这样的变量:
constructor(props) {
super(props);
this.state = {
triggeredSections: []
};
this.camerasRefs = [];
}
所以我最终可以使用这个数组访问我的CamaraLenta组件。
handleRepeat(index) {
this.camerasRefs[index].handleRepeat();
}
感谢您的帮助和理解!