首页 > 解决方案 > 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} “&lt;/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.

标签: javascriptreactjs

解决方案


您可以使用功能组件来简化此操作。然后使用 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]} “&lt;/p>  
      </div>
      <button type="button" onClick={setNewQuote}>New Quote</button>
    </div>
  );


推荐阅读