首页 > 解决方案 > 点击时反应获取组件道具

问题描述

嗨,我正在创建一个应用程序,用户可以在其中搜索一本书并将其放在书架上,具体取决于用户点击的书架。目前,用户可以键入查询,并且可以显示许多结果。我希望用户在一本书的下拉菜单中单击一个书架(在下拉菜单中)以选择该书并将其移动到该书架。

我现在要做的是在用户单击下拉选项(这是一个书架)时检索图书对象。我想将这本书对象传递给 api 调用。当用户单击特定书籍的下拉选项时,我将如何检索书籍对象?我知道这可能涉及事件冒泡。我希望这个问题是有道理的。

搜索页面.js

import React, { useEffect, useState } from 'react';
import { BsArrowLeftShort } from 'react-icons/bs';
import SearchBar from '../components/SearchBar';
import { search, update, getAll } from '../api/BooksAPI';
import Book from '../components/Book';

const SearchPage = () => {
  const [query, setQuery] = useState('');
  const [data, setData] = useState([]);

  const handleChange = (e) => {
    setQuery(e.target.value);
  };

  useEffect(() => {
    const bookSearch = setTimeout(() => {
      if (query.length > 0) {
        search(query).then((res) => {
          if (res.length > 0) {
            setData(res);
          } else setData([]);
        });
      } else {
        setData([]); 
      }
    }, 1000);
    return () => clearTimeout(bookSearch);
  }, [query]);

  const [shelfType, setShelfType] = useState('None');
  const [currentBook, setCurrentBook] = useState({});

  const handleShelfTypeClick = (e) => {
    setShelfType(e.target.value);
    console.log(e.target.parentElement.parentElement.parentElement);
  //here I want to retrieve the book object when the user clicks on a dropdown option (shelf)
  }; 

  return (
    <div>
      <SearchBar
        type="text"
        searchValue={query}
        placeholder="Search for a book"
        icon={<BsArrowLeftShort />}
        handleChange={handleChange}
      />
      <div className="book-list">
        {data !== []
          ? data.map((book) => (
              <Book
                handleShelfTypeClick={handleShelfTypeClick}
                book={book}
                key={book.id}
              />
            ))
          : 'ok'}
      </div>
    </div>
  );
};

export default SearchPage;

Book.js

import React from 'react';
import PropTypes from 'prop-types';
import ButtonDropDown from './ButtonDropDown';

const Book = ({ book, handleShelfTypeClick }) => {

  return (
    <div className="book">
      <img
        src={book.imageLinks.thumbnail}
        alt={book.title}
        className="book-thumbnail"
      />
      <ButtonDropDown
        choices={['Currently Reading', 'Want to Read', 'Read', 'None']}
        getShelfType={handleShelfTypeClick}
      />
      <div className="book-title">{book.title}</div>
      <div className="book-authors">{book.authors}</div>
    </div>
  );
};

Book.propTypes = {
  handleShelfTypeClick: PropTypes.func.isRequired,
  book: PropTypes.shape({
    imageLinks: PropTypes.shape({
      thumbnail: PropTypes.string.isRequired,
    }),
    title: PropTypes.string.isRequired,
    authors: PropTypes.arrayOf(PropTypes.string),
  }).isRequired,

};

export default Book;

ButtonDropDown.js

import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { BsFillCaretDownFill } from 'react-icons/bs';

const ButtonDropDown = ({ choices, label, getShelfType }) => {
  const [active, setActive] = useState(false);

  const toggleClass = () => {
    setActive(!active);
  };

  return (
    <div className="dropdown">
      <button
        type="button"
        className="dropbtn"
        onFocus={toggleClass}
        onBlur={toggleClass}
      >
        <BsFillCaretDownFill />
      </button>
      <div
        id="myDropdown"
        className={`dropdown-content ${active ? `show` : `hide`}`}
      >
        <div className="dropdown-label">{label}</div>
        {choices.map((choice, index) => (
          <button
            // eslint-disable-next-line react/no-array-index-key
            key={index}
            className="dropdown-choice"
            onClick={getShelfType}
            type="button"
            value={choice}
          >
            {choice}
          </button>
        ))}
      </div>
    </div>
  );
};

ButtonDropDown.propTypes = {
  choices: PropTypes.arrayOf(PropTypes.string).isRequired,
  label: PropTypes.string,
  getShelfType: PropTypes.func.isRequired,
};

ButtonDropDown.defaultProps = {
  label: 'Move to...',
};

export default ButtonDropDown;

标签: javascriptreactjseventsonclickreact-props

解决方案


您专注于onClick事件的签名,但实际上您可以使用所需的任何格式传递回调,然后动态构建onClick

例如,Book您可以有一个接收书籍和书架的回调:

const Book = ({ book, doSomethingWithBookAndShelf }) => {

  return (
    <div className="book">
      <img
        src={book.imageLinks.thumbnail}
        alt={book.title}
        className="book-thumbnail"
      />
      <ButtonDropDown
        choices={['Currently Reading', 'Want to Read', 'Read', 'None']}
        onSelectChoice={(choice) => {
           // book came from the component props
           doSomethingWithBookAndShelf(book, choice);
        }}
      />
      <div className="book-title">{book.title}</div>
      <div className="book-authors">{book.authors}</div>
    </div>
  );
};

并在ButtonDropDown

const ButtonDropDown = ({ choices, label, onSelectChoice }) => {
  const [active, setActive] = useState(false);

  const toggleClass = () => {
    setActive(!active);
  };

  return (
    <div className="dropdown">
      <button
        type="button"
        className="dropbtn"
        onFocus={toggleClass}
        onBlur={toggleClass}
      >
        <BsFillCaretDownFill />
      </button>
      <div
        id="myDropdown"
        className={`dropdown-content ${active ? `show` : `hide`}`}
      >
        <div className="dropdown-label">{label}</div>
        {choices.map((choice, index) => (
          <button
            // eslint-disable-next-line react/no-array-index-key
            key={index}
            className="dropdown-choice"
            onClick={() => { // we create an specific callback for each item
              onSelectChoice(choice);
            }}
            type="button"
            value={choice}
          >
            {choice}
          </button>
        ))}
      </div>
    </div>
  );
};

希望这能让你朝着某个方向前进。另外,请注意它更像 React 那样工作。避免使用事件对象来获取值(即e.target.value)。


推荐阅读