【发布时间】:2017-06-17 18:06:29
【问题描述】:
我正在尝试为我在 array.map 上呈现的组件提供一个引用,以便稍后我可以调用这些组件中的一些函数。
同一个组件会有 3 个实例,当给它们一个 ref 时我得到了这个错误:
Uncaught Error: Stateless function components cannot have refs.
这里,父组件的 render 方法试图渲染这 3 个子组件:
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",
【问题讨论】:
-
如果我删除对我正在渲染的 CamaraLenta 组件的引用,错误就会消失,但我以后不能从父级使用它们,当然......
-
那是因为无状态函数无权访问这个关键字或引用
-
我不明白。两个组件都有状态,所以它们不是无状态的。
-
您的整体组件可能是,但您的 ElementsContainer 是无状态组件
标签: reactjs components