React Native 我需要选择和捕捉按钮的ID(可触摸的不透明度)选定

omhiaaxx  于 2023-03-24  发布在  React
关注(0)|答案(1)|浏览(154)

我需要选择一个按钮并获取其特定的ID来删除它。然而,在第一次执行后,被排除的按钮的ID被保留,而不是另一个被选择的按钮。
我需要一种方法来获取我所选项目的id

<View>

type BookProps = {
    id: string;
    name: string;
    description: string;
    updatedAt: string;
    authorId: string;
  }
  
const [books, setBooks] = useState<BookProps[] | []>([])

{books.map((book, index) => <BookItem key={index} bookId={book.id} name={book.name} description={book.description} updatedAt={book.updatedAt} />)}
</View>

组件在这里:

export default function BookItem({ name, description, bookId, updatedAt}: BookProps) {

function deleteItem(bookId: string){

}

return(
<TouchableOpacity onPress={deleteItem} >
        <Text>{name}</Text>
        <Text>{description}</Text>
        <Text>{updatedAt}</Text>
</TouchableOpacity>
)}
cygmwpex

cygmwpex1#

您必须从父级传递一个 onDelete 函数,以从 books 状态中删除一个项目。

const ParentComponent = () => {
  const [books, setBooks] = useState<BookProps[] | []>([])

  const handleDeleteBook = (bookId: string) => {
    setBooks(books.filter(book => book.id !== bookId));
  }

  return (
    <View>
      {books.map((book, index) => (
        <BookItem
          key={index}
          bookId={book.id}
          name={book.name}
          description={book.description}
          updatedAt={book.updatedAt}
          onDelete={handleDeleteBook}
        />
      ))}
    </View>
  );
}

type BookItemProps = BookProps & {
  onDelete: (bookId: string) => void;
}

export default function BookItem({ name, description, id, updatedAt, onDelete }: BookItemProps) {

  const deleteItem = () => {
    onDelete(id);
  }

  return (
    <TouchableOpacity onPress={deleteItem}>
      <Text>{name}</Text>
      <Text>{description}</Text>
      <Text>{updatedAt}</Text>
    </TouchableOpacity>
  )
}

相关问题