我有一个react组件,该组件旨在使子组件在每次调用该子组件之间有很小的延迟。此延迟将更改延迟呈现的内容。我似乎无法弄清楚如何在应用到数组的映射函数内部进行的每次迭代中获得该延迟。这是我的代码:
import React, { Component } from "react";
import ImageListItem from "./imageListItem"
import styles from "../../css/carousel/imageList.css"
export default function Option (props) {
return(
<div>
<div style={styles.ImageList}>
<div style={styles.ImageTemplate}>
<button style={styles.ImageTempalateButton}>
<img style={styles.ImageTemplateImage} src="" alt=""/>
</button>
</div>
{
props.images.map((image) => (
<div key={image._id}>
<ImageListItem currImage={image} waitBeforeShow={2000}/>
</div>
))
}
</div>
</div>
)
}
我希望每次ImageListItem都被延迟。我该如何做出反应?
答案 0 :(得分:0)
只有在计时器完成后,您才能在ImageListItem
和conditionally render中设置计时器。
一些注意事项:
(index + 1) * deleyMs
这是一个小的概念证明:
const items = [1, 2, 3, 4, 5, 6];
class Item extends React.Component {
state = { shouldRender: false }
componentDidMount() {
const { deleyMs } = this.props;
this.timer = setTimeout(() => {
this.setState({ shouldRender: true });
}, deleyMs);
}
componentWillUnMount(){
// cleanup
clearTimeout(this.timer);
}
render() {
const { text } = this.props;
const { shouldRender } = this.state;
return (
<div>
{shouldRender && text}
</div>
)
}
}
function App() {
return (
<div>
{
items.map((item, i) => <Item key={item} text={item} deleyMs={(i + 1) * 2000} />)
}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"/>