以下是用户界面,我试图在其中延迟1秒后显示每个框-(Box1、1秒延迟,Box2、1秒延迟,Box3等)
相反,我得到-
我的React代码,让我知道我在做什么错&为什么显示数字-
const CreateBox = (props) => {
return (
<>
{/*<div className="box">{props.num}</div>*/}
<div className="box"></div>
</>
)
}
const App = () => {
return (
<div className="app">
<h3>App</h3>
{
[1,2,3,4,5,6,7,8,9,10].map((item) => {
return setTimeout(() => {
// return (<CreateBox num={item} />)
return (<CreateBox />)
}, 1000)
})
}
</div>
)
}
const root = document.querySelector('#root')
ReactDOM.render(<App />, root)
答案 0 :(得分:3)
您可以在componentDidMount
中创建一个间隔,并在状态中递增一个数字直到达到10,而不是在每个渲染中为数组中的每个元素创建新的超时,而在渲染方法中使用此数字
示例
class App extends React.Component {
state = {
count: 0
};
componentDidMount() {
const interval = setInterval(() => {
this.setState(
({ count }) => ({ count: count + 1 }),
() => {
if (this.state.count === 10) {
clearInterval(interval);
}
}
);
}, 1000);
}
render() {
return (
<div className="app">
<h3>App</h3>
{Array.from({ length: this.state.count }, (_, index) => (
<CreateBox key={index} num={index + 1} />
))}
</div>
);
}
}
const CreateBox = props => {
return <div className="box">{props.num}</div>;
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
答案 1 :(得分:2)
const CreateBox = (props) => {
return (
<div className="box">{props.num}</div>
)
}
const App = () => {
return (
<div className="app">
<h3>App</h3>
{
[1,2,3,4,5,6,7,8,9,10].map((item) => {
return (<CreateBox num={item} />)
})
}
</div>
)
}
const root = document.querySelector('#root')
ReactDOM.render(<App />, root)
答案 2 :(得分:0)
循环时不要使用setTimeout。而是使用状态在CreateBox组件内设置计时器。如果您删除超时,则可以看到方框。要处理延迟,请将index * 1000用作每个元素的计时器。
答案 3 :(得分:0)
class CreateBox extends React.Component {
state = {
opacity: 0
}
constructor(props){
super(props)
}
componentDidMount(){
setTimeout(()=> this.setState({opacity: 1}),`${this.props.time}000`)
}
render() {
console.log(this.props)
return (
<div style={this.state} className="box">{this.props.num}</div>
)
}
};
const App = () => {
return (
<div className="app">
<h3>App</h3>
{
[1,2,3,'w',5,6,7,8,9,10].map((item, index) => <CreateBox num={item} time={index}/>)
}
</div>
)
}
const root = document.querySelector('#root')
ReactDOM.render(<App />, root)