我遇到了一个我无法理解的错误,它是关于一个接受数组并从中返回随机值的函数。我上次用了同样的功能,没有出现这个错误
helpers.js
function choice(arr) {
let randomIndex = Math.floor(Math.random() * 3);
return arr[randomIndex];
}
export { choice };
box.js
import React, { Component } from 'react';
import {choice} from './helpers';
import './Box.css'
class Box extends Component {
static defaultProps = {
allColors: ["purple", "magenta", "violet", "pink"]
};
constructor(props){
super(props);
this.state = {color: choice(this.props.allcolors)};
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
}
render(){
return(
<div className="Box" style={{backgroundColor: this.state.color}
} onClick={this.handleClick}>
</div>
);
}
}
export default Box;
最佳答案
你的代码有两个错误:
this.props.allcolors
是undefined
,因为您已经将 PropallColors
设置为大写的“C”- 这在您的特定情况下可能不是问题,但一般来说,函数
choice
不会给您想要的结果。它现在仅适用于长度为 3 的数组。要解决此问题,您可以将3
更改为arr.length
,如下所示:
function choice(arr) {
let randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
}
关于javascript - 在一个接受数组并返回随机值的简单函数中 react js错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59337254/