简体   繁体   中英

Toggle two different functions on a single onClick in reactjs

I have two different functions

  bookmark = () => {
//logic for bookmark
}

  bookmarkRemove = () => {
//logic for bookmark remove
}

    return (
      <div>
   <img src={bookamark} alt="bookmark" onClick={}
</div>
)

When I first click, I want to trigger bookmark() , and second time If I click the same image, it should trigger bookmarkRemove() and third-time bookmark() and so forth

there are mutliple ways to do it, but i will use closure to demonstrate

onClick={ toggleBookmark() }

function toggleBookmark() {
  let bookmarked  = false; // take default value from state 
  return function () {
    bookmarked ? bookmarkRemove() : bookmark();
    bookmarked = !bookmarked;
  }
}

now you can keep this bookmarked state in component as well

You can create a state to check and trigger function you want.

 import React, { useState } from "react"; import "./styles.css"; export default function App() { const [isBookMakred, setIsBookMakred] = useState(false); const bookmark = () => { //logic for bookmark }; const bookmarkRemove = () => { //logic for bookmark remove }; const handleOnclick = () => { if (isBookMakred) { bookmarkRemove(); setIsBookMakred(false); } else { bookmark(); setIsBookMakred(true); } }; return ( <div> <img src="image_url" alt="bookmark" onClick={handleOnclick} /> </div> ); }

Make a toggle state variable, and change it whenever the function is triggered.

import React, { useState } from "react";

export default function App() {
  const [toggle, setToggle] = useState(false);

  function toggleFunction(){
    if(toggle) bookmarkRemove()
    else bookmark()
    setToggle(!toggle)
  }

  return (
    <img src={bookamark} alt="bookmark" onClick={toggleFunction}
  );
}

set a toggle in the state

    const [toggle, setToggle] = useState(true)
    bookmark = () => { setToggle(false) //other logic }
    bookmark = () => {setToggle(true) //other logic}


    return (
          <div>
       <img src={bookmark} alt="bookmark" 
    onClick={(toggle) => toggle? this.bookmark: this.bookmarkRemove}>
    </div>
    )
// local state..
state = {
 bookmark: true,
}

// execute based on the state and then toggle it..
handleBookMark = () => {
 this.state.bookMark ? bookMark() : removeBookMark();

 this.setState((prevState) => {
  ...prevState,
  bookmark:!this.state.bookmark, 
 })
}

<div onClick={() => this.handleBookMark()}>
 <img ... />
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM