功能化合物成分

时间:2019-07-17 15:10:52

标签: reactjs

我想练习我的反应技巧,并熟悉复合组件和功能组件中的新API。 为了练习,我创建了一个典型的FAQ部分。我希望用户通过单击一个问题一次只能扩展一个答案。

在此示例中,我不知道如何识别每个问题/答案来触发切换,而无需在每个组件上提供键或名称。

    <FaqPanel>
      <Faq>
        <Faq.Question>Question 1</Faq.Question>
        <Faq.Answer>Answer 1</Faq.Answer>
      </Faq>
      <Faq>
        <Faq.Question>Question 2</Faq.Question>
        <Faq.Answer>Answer 2</Faq.Answer>
      </Faq>
      <Faq>
        <Faq.Question>Question 3</Faq.Question>
        <Faq.Answer>Answer 3</Faq.Answer>
      </Faq>
    </FaqPanel>
import React, { useState, createContext, useContext } from "react";

import styled from "styled-components";

const Qs = styled.p`
  width: 100%;
  border: solid 2px;
`;

const As = styled.p`
  display: ${props => (props.visible ? "grid" : "block")};
`;

const FaqContext = createContext();

const FaqPanel = props => {
  const { children } = props;

  const [activeQuestion, changeQuestion] = useState();
  const providerValues = { activeQuestion, changeQuestion };

  return (
    <FaqContext.Provider value={providerValues}>
      <div>{children}</div>
    </FaqContext.Provider>
  );
};

const Faq = props => {
  const { children } = props;
  return <div>{children}</div>;
};

const Question = props => {
  const faqContext = useContext(FaqContext);

  function handleClick() {
    faqContext.changeQuestion();
  }

  return <Qs onClick={handleClick()}>{props.children}</Qs>;
};

const Answer = props => {
  const faqContext = useContext(FaqContext);

  return <As visible={faqContext.activeQuestion}>{props.children}</As>;
};

Faq.Question = Question;
Faq.Answer = Answer;

export { FaqPanel, Faq };

0 个答案:

没有答案
相关问题