网站搜索

reactjs - 在点击处理函数中获取属性值?


我如何获取eventKey属性的值并将其传递给下一行中的函数?

<Accordion.Toggle 
   as={Card.Header} 
   eventKey="2" 
   data-foo="zzz" 
   onClick={(e) => CardClick(e.currentTarget.getAttribute('eventKey') ?? "unknown")}> // unknown.  Desired value: 2

这个问题中提到了以下内容。然而,在我的情况下,我需要获取的属性并没有以“data-”为前缀。

作品:

<Accordion.Toggle 
   as={Card.Header} 
   eventKey="2" 
   data-foo="zzz" 
   onClick={(e) => CardClick(e.currentTarget.getAttribute('data-foo') ?? "unknown")}> // zzz 

不工作:

<Accordion.Toggle 
   as={Card.Header} 
   eventKey="2" 
   data-foo="zzz" 
   onClick={(e) => CardClick(e.currentTarget.getAttribute('data-eventKey') ?? "unknown")}> // unknown

完整组件:

<Card>
    <Accordion.Toggle as={Card.Header} eventKey="0" className="faq-header" onClick={(e) => CardClick(e.currentTarget.getAttribute('eventKey') ?? "unknown")}>
        <span className="rh5">Some text</span>
    </Accordion.Toggle>
    <Accordion.Collapse eventKey="0">
        <Card.Body>
            <span className="rh6">
                Some text
            </span>
        </Card.Body>
    </Accordion.Collapse>
</Card>

答案#1

正如 @DrewReese 在评论中解释的那样,不可能从 DOM 元素 (e.target) 获取 eventKey,因为它从未传递到 DOM。

我们应该从 props 中获取它。我们确实需要在三个地方使用 eventKey:作为 Toggle 和 Collapse 中的 eventKey 属性,以及在我们的 onClick 中。但当它被抽象为组件属性时,我们只需要声明特定的事件键,即 eventKey="2",一次即可。

import React from "react";
import { Accordion, Card } from "react-bootstrap";

interface RenderCardProps {
  eventKey: string;
  CardClick: (key: string) => void;
  /** add whatever else you need */
}

const RenderCard = ({ eventKey, CardClick }: RenderCardProps) => {
  return (
    <Card>
      <Accordion.Toggle
        as={Card.Header}
        eventKey={eventKey}
        className="faq-header"
        onClick={() => CardClick(eventKey)}
      >
        <span className="rh5">Some text</span>
      </Accordion.Toggle>
      <Accordion.Collapse eventKey={eventKey}>
        <Card.Body>
          <span className="rh6">Some text</span>
        </Card.Body>
      </Accordion.Collapse>
    </Card>
  );
};

export default () => <RenderCard CardClick={console.log} eventKey="2" />;

你可能也想把 ToggleContents 和 CardContents 作为 props,这样才能将其作为一个实际的组件使用。