Ниже приведен пример реакционного крючка, который отвечает за то, чтобы сделать пурпурную кнопку фиолетовым в двух разных компонентах. Я использую это в моем Проект Что вы можете играть Здесь Анкет
import { useState } from 'react';
// hook code
function useMoveUpdate() {
const [currentMove, setCurrentMove] = useState('');
const newMove = (event) => {
event.preventDefault();
let move = event.currentTarget.value;
let theVictim = null;
if (event.currentTarget.value.includes('leave_comment')) {
move = 'leave_comment';
theVictim = event.currentTarget.id;
}
setCurrentMove(event.currentTarget.value);
};
return [currentMove, newMove];
}
import React from 'react';
import useMoveUpdate from '../hooks/CurrentMove';
function GameMoves({
game, dispatch
}) {
// component that uses the hook
const [currentMove, newMove] = useMoveUpdate();
return (
{['post_selfie', 'dont_post', 'go_live'].map(item => (
))}
);
}
import React from 'react';
import { Phone } from '../images/iPhone';
import useMoveUpdate from '../hooks/CurrentMove';
function GameBox({ game, dispatch}) {
// component that uses the hook
const [currentMove, newMove] = useMoveUpdate();
return (
{game.users.map(player => (
{player.username}
{!game.round_started && (player.started ? '!' : ' ?')}
{player.followers}
{player.followers === 1 ? 'follower' : 'followers'}
{player.stories}
{player.stories === 1 ? 'story' : 'stories'}
{' '}
))}
);
}
Как это работает.
const [currentMove, setCurrentMove] = useState('');
CurrentMove Удерживает значение, какая кнопка должна быть фиолетовой и SetCurrentMove выполняет действие, определенное в крючке.
Состояние начального крючка – это пустая строка, что означает, что все кнопки зеленые, потому что ClassName это то, что меняется, когда нажата кнопка. ClassName диктует CSS.
Крюк возвращает [CurrentMove, Newmove] и это то, что UseMoveUpdate Возвращает в компонентах. Нажатие кнопки выполняет newmove Действие, которое обновляет нажатие кнопки, которая изменяет его цвет.
Вот пример его работы в моем проекте:
Оригинал: “https://dev.to/aduranil/react-custom-hooks-sharing-logic-between-components-19o8”