Как реагировать, как я могу разрешить только один из родственных компонентов одновременно - PullRequest
0 голосов
/ 28 января 2020

У меня есть несколько из этих компонентов, отображаемых на странице с собственным расширением состояния, которое может быть установлено в true и false. Как ограничить компоненты так, чтобы только один из компонентов мог быть активным одновременно. Я использую стайлинг-компоненты, которые проверяют, активен ли он, прежде чем применить новый CSS. В настоящее время каждый покемон просто перекрывает друг друга при нажатии.

Current site

Компонент

export default function Image(props) {
  const [expand, setExpand] = useState(false);

  const Li = styled.li`
  width: 50px;
  height: 50px;
  margin: 25px;

  box-sizing: border-box;
  ${expand !== true}{
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    width: 500px;
    height: 500px;
  }
`;

  const H3 = styled.h3`
    text-align: center;
    display: none;
    font-size: 4rem;
    margin: 0;
    text-transform: capitalize;
    ${expand !== true}{
      display: block;
    }
  `;

  const H5 = styled.h5`
    text-align: center;
    display: none;
    font-size: 3rem;
    margin: 0;
    text-transform: capitalize;
    ${expand !== true}{
      display: block;
    }
  `;

  const Img = styled.img`
  width: 100%;
  height: 100%;
  cursor: pointer;
  object-fit: cover;
`;

  return (
    <Li>
      <Img draggable={false} src={props.src} onClick={() => { setExpand(!expand); }} />
      <H3>{props.name}</H3>
      <H5>{props.types}</H5>
    </Li >
  )
}

Main

//Styling
const Section = styled.section`
  margin-top: 50px;
`;

const Ul = styled.ul`
  margin:0;
  padding:0;
  list-style:none;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
`;

const Main = styled.main`
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
`;

export default function Test() {
  //States
  const [pokemonArray, newPokemon] = useState([]);

  //Hooks
  useEffect(() => {
    (async () => {
      const dataArray = [];
      for (let i = 1; i < 25; i++) {
        let data = await fetch('https://pokeapi.co/api/v2/pokemon/' + i).then(res => res.json());
        dataArray.push(data);
      }

      newPokemon(dataArray);
    })()
  }, []);

  //Render
  return (
    <Route exact path="/pokedex">
      <Main>
        <Section>
          <Ul>
            {articleTemplate()}
          </Ul>
        </Section>
      </Main>
    </Route>
  );

  //Functions
  function articleTemplate() {
    const components = []
    pokemonArray.forEach((elm, index) => {
      const array = [];
      elm.types.forEach(type => {
        array.push(type.type.name);
      })

      components.push(<Li key={index} src={elm.sprites.front_default} name={elm.name}
        types={array.join('/')} />)
    })
    return components;
  };
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...