javascript - Is there a way to cycle through elements in an array using the onClick function in react
问题描述
I have an array of data.
const quotes = [
{"author": "Marilyn Monroe",
"quote" : "I'm selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle. But if you can't handle me at my worst, then you sure as hell don't deserve me at my best." },
{"author" : "Oscar Wilde",
"quote" : "Be yourself, everyone else is already taken."}
]
I want to render an individual object to a div. I then want to cycle through the objects in the array when i click on the button
This is what I have tried so far :
class ‘MyComponent extends React.Component {
constructor(props) {
super(props);
this.sayHello = this.sayHello.bind(this);
}
sayHello() {
return quotes[(Math.floor(Math.random() * Math.floor(quotes.length)))];
}
render() {
return (
<div className="body">
<div className="quote">
<p>“ {this.sayHello.quote} “</p>
</div>
<button type="button" onClick={this.sayHello.quotes.quote}>New Quote</button>
</div>
);
}
};
function Create(props){ return ( {this.sayHello.author} ) };
I want to be able to get a new object rendered to the div when I click the button. I'm extremely new to react. Thanks in advance for all your help.
解决方案
您可以使用功能组件来简化此操作。然后使用 useState 挂钩来跟踪您正在显示的报价。然后使用回调函数为单击按钮时的状态随机分配一个引号。这是一个例子。
import React from "react"
const quotes = [{
author: "Marilyn Monroe",
quote: "I'm selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle. But if you can't handle me at my worst, then you sure as hell don't deserve me at my best."
}, {
author: "Oscar Wilde",
quote: "Be yourself, everyone else is already taken."
}];
export const MyComponent = (props) =>{
const [quoteIndex, setQuoteIndex] = React.useState(0);
const setNewQuote = () => {
setQuoteIndex(Math.floor(Math.random() * quotes.length));
}
return (
<div className="body">
<div className="quote">
<p>“ {quotes[quoteIndex]} “</p>
</div>
<button type="button" onClick={setNewQuote}>New Quote</button>
</div>
);
推荐阅读
- java - 使用 html 字符串生成 PDF
- wordpress - 将所有 Woocommerce 订单从“保留”更改为“完成”
- amazon-web-services - 使用 Cloudflare 通过通配符记录子域访问 AWS S3
- excel - VBA循环遍历行然后列
- php - php将一个多维数组与自身相加
- android - “ionic cordova run android”卡住了
- python - 如何使用python根据输入值划分数组
- python-3.x - google-cloud-logging 模块未记录到 StackDriver 中正确的严重性过滤器
- python - Scrapy Splash 屏幕截图管道不起作用
- javascript - 将纬度和经度转换为 XY 坐标