javascript - 在 React 中从数组中渲染特定元素
问题描述
我的目标是有一个框,可以在数组中按顺序呈现颜色的单词。
我正在为渲染数组的每个元素的概念而苦苦挣扎。我假设您需要挑选每个元素,将其存储在一个变量中,然后渲染该变量,但每次我尝试它时都会遇到死胡同。
您将在下面的代码中看到我注释掉的尝试。我也尝试过forEach
,但 React 在尝试使用forEach
.
此外,我被告知避免使用.map
and afor loop
如果可能的话。
import React from 'react'
class ColorSwitch extends React.Component {
constructor(props) {
super(props)
this.state = {
colors: ["white", "orange", "purple", "black", "green"]
}
}
nextColor = () => {
let newColor = this.state.colors
// let setColor = newColor[0] += 1 (DIDNT WORK)
this.setState({colors: setColor})
}
render() {
let { colors } = this.state
return(
<div className="box" onClick={this.nextColor}>
<p>{this.setColor}</p>
</div>
)
}
}
export default ColorSwitch
在此先感谢您的帮助。
解决方案
从道具中获取颜色(如果它是静态的,则使用 const),并将其存储在currentColorIndex
内部状态。
调用时按 1nextColor
递增currentColorIndex
(我使用 % colors.length 进行下一个循环)。要渲染抓取颜色currentColorIndex
:
const colors = ["white", "orange", "purple", "black", "green"]
class ColorSwitch extends React.Component {
state = {
currentColorIndex: 0
}
nextColor = () =>
this.setState(({ currentColorIndex }) => ({
currentColorIndex: (currentColorIndex + 1) % this.props.colors.length
}))
render() {
const { currentColorIndex } = this.state
const { colors } = this.props
const color = colors[currentColorIndex];
return(
<div className="box"
onClick={this.nextColor}
style={{ background: color }}>
<p>{color}</p>
</div>
)
}
}
ReactDOM.render(
<ColorSwitch colors={colors} />,
demo
)
<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="demo"></div>
推荐阅读
- angular - 如何解决错误 ng-snotify 在从 8 更新到 Angular 9 之前具有不兼容的对等依赖项?
- ios - 按钮边框颜色不会更改为自定义颜色
- node.js - 在 sequelize 中定义自定义验证
- ionic-framework - 菜单中的 useIonViewDidEnter 在 ionic-react 中不起作用
- google-cloud-platform - GCP 签名 URL 的 CORS 问题
- python - 如何从python中的HTML中提取时间类?
- python - 关于使用python3的列表列表的问题
- python - 以编程方式更改 Python 控制台的字体
- smarty - 如何在 Smarty 数组的循环中获取最后一次迭代之前的项目
- c# - 向 InvalidOperationException 行添加更多信息