我试图在单击按钮时生成输入,并且输入数量由随机数生成。这是我到目前为止的内容,但是没有用。我很困惑,觉得它应该工作。我不确定我缺少什么。任何帮助将不胜感激。
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { Image } from './Image.js'
import { Button } from './Button.js'
import { images } from './assets/images.js'
import { Countdown } from './Countdown.js'
import { DisplayCount } from './DisplayCount.js'
import { Inputs } from './Inputs.js'
class Game extends React.Component{
constructor(props){
super(props)
this.timer = null
this.state = {
currentImg: 0,
timer: null,
ranNum: null
}
this.handleClick = this.handleClick.bind(this)
}
countdownClock = async (newRanNum) => {
const startingNum = newRanNum * 20;
for(let i = startingNum; i >= 0; i--) {
await new Promise(resolve => {
this.timer = setTimeout(() => {
this.setState({
timer: i
})
resolve()
}, 1000)
});
}
}
generateInputs = (newRanNum) => {
const inputs = []
for(let i = 1; i <= newRanNum; i++){
inputs.push(
<Inputs type='text' className='textInputs' />
)
}
return inputs;
}
handleClick(){
clearTimeout(this.timer)
let newRanNum = Math.floor(Math.random() * 20);
this.countdownClock(newRanNum)
this.generateInputs(newRanNum)
let current = this.state.currentImg;
let next = ++current % images.length;
this.setState({
currentImg: next,
ranNum: newRanNum
})
}
render(){
let src = this.state.currentImg;
return(
<div>
<Countdown name={'Countdown: '} countdown={this.state.timer} />
<DisplayCount name='Word Count: ' count={this.state.ranNum} />
<Image src={images[src]} />
<Button onClick={this.handleClick} />
<div>
<ul>
{this.generateInputs()}
</ul>
</div>
</div>
)
}
}
ReactDOM.render(
<Game />,
document.getElementById('root')
);
输入组件:
import React from 'react'
export const Inputs = (props) => {
return (
<li className={props.className}>
<input value={props.value} />
</li>
)
}
我相信问题在这里...
generateInputs = (newRanNum) ...
和这里...
{this.generateInputs()}
您正在输入渲染函数,期望它没有得到一个参数,由于该参数返回为undefined
,因此循环永远不会运行。 :)
通常,最常见的是将状态(例如,输入的数量)与渲染分开,并且仅使渲染[[响应处于状态。也许您最初打算使用generateInputs()
来生成数组,而不渲染它们(?)
generateInputs()
函数采用一个参数,该参数表示您想要将but you are not passing any parameter
渲染为this.generateInputs()
的输入数量第二件事是您从此函数返回一个数组,但未在render函数中映射您的数组,因此请按照这种方式进行。
this.generateInputs(10) // pass parameter here
this.generateInputs(10).map((item, index)=>item)
在本次点心中,我做了同样的事情,但使用react-native