function Typewriter({ text }) {
const [ length, setLength ] = useState(0);
useEffect(() => {
setLength(0);
const interval = setInterval(setLength, 100, length => {
if (++length >= text.length) {
clearInterval(interval);
}
return length;
});
return () => clearInterval(interval);
}, [ text ]);
return <div>{text.slice(0, length)}</div>;
}
nextEl: prevRef.currentconst [ swiper, setSwiper ] = useState();<Swiper
onSwiper={setSwiper}
...- ref={prevRef}
+ onClick={() => swiper.slidePrev()}
срабатывает дважды, а в последующие разы увеличивается в разы
useEffect(() => { window.addEventListener('keydown', onKeyPress); }, [focus])
useEffect(() => {
const onKeyDown = e => {
if (e.key === 'ArrowRight') {
setFocus(focus => focus + 1);
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, []);
state = {
phones: [
{ id: 1, title: '', number: '' },
],
}
onChange = ({ target: { value, name, dataset: { index } } }) => {
this.setState(({ phones }) => ({
phones: phones.map((n, i) => +index === i
? { ...n, [name]: value }
: n
),
}));
}
addPhone = () => {
this.setState(({ phones }) => ({
phones: [
...phones,
{
id: 1 + Math.max(...phones.map(n => n.id)),
title: '',
number: '',
},
],
}));
}
delPhone = ({ target: { dataset: { index } } }) => {
this.setState(({ phones }) => ({
phones: phones.filter((n, i) => i !== +index),
}));
}
render() {
return (
<div>
{this.state.phones.map((n, i) => (
<div key={n.id}>
<input name="title" data-index={i} value={n.title} onChange={this.onChange} />
<input name="number" data-index={i} value={n.number} onChange={this.onChange} />
{i ? <button data-index={i} onClick={this.delPhone}>x</button> : null}
</div>
))}
<button onClick={this.addPhone}>Add</button>
</div>
);
}
Что я делаю не так
как решить проблему?
{ LikeIcon } ---> <LikeIcon />.
const [ todos, setTodos ] = useState(() => {
let todos = null;
try {
todos = JSON.parse(localStorage.getItem('todos'));
} catch (e) {};
return Array.isArray(todos) ? todos : [];
});setTodos([ ...todos, { id: Date.now(), complete: false, title: value, }, ]); localStorage.setItem("todos", JSON.stringify(todos));
useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todos));
}, [ todos ]);
сделал две функции, которые поочерёдно возвращают компонент согласно индексу
желаемого эффекта не получил
в консоль выводиться...
const Component1 = () => <h1>hello, world!!</h1>;
const Component2 = () => <h1>fuck the world</h1>;
const Component3 = () => <h1>fuck everything</h1>;
const components = [ Component1, Component2, Component3 ];
function App() {
const [ index, setIndex ] = useState(0);
const min = 0;
const max = components.length - 1;
const Component = components[index];
const onClick = ({ target: { dataset: { step } } }) =>
setIndex(Math.max(min, Math.min(max, index + +step)));
return (
<div>
<button onClick={onClick} data-step="-1" disabled={index <= min}>prev</button>
<button onClick={onClick} data-step="+1" disabled={index >= max}>next</button>
{Component && <Component />}
</div>
);
}
const [ buttonText, setButtonText ] = useState('hello, world!!');
const [ clicked, setClicked ] = useState(false);
function onClick() {
setClicked(true);
setTimeout(() => {
setButtonText('fuck the world');
setClicked(false);
}, 1000);
}<button onClick={onClick} disabled={clicked}>{buttonText}</button>
{clicked ? <img src="..." /> : null}
useCapture
A boolean value indicating whether events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
element.addEventListener(event, handler, true).
React.useCallback((key, val) => {
setData(data => ({
...data,
[key]: val(data[key]),
}));
}, [])onChange('list', list => list.map((n, i) => i === index
? { ...n, [prop]: value }
: n
))onChange('description', () => e.target.value)
Вначале удаляем элемент из массива, затем выбираем новый. Но получается так, что, иногда, выбор случайного элемента массива, происходит до удаления элемента из массива и он выбирает только что удаленный элемент.
Как правильно реализовать такую логику?
useEffect(() => {
dispatch({
type: SET_RND_NUM,
payload: state.arr[Math.random() * state.arr.length | 0],
});
}, [ state.arr ]);
const [ checked, setChecked ] = React.useState(false);<input
type="checkbox"
checked={checked}
onChange={e => setChecked(e.target.checked)}
...<button
disabled={!checked}
...
const Todos = ({ todos, TodoItem }) => (
<div className="todos">
{todos.map(n => (
<div className="todo-item" key={n.id}>
<TodoItem todo={n} />
</div>
))}
</div>
);const HeaderTodoItem = ({ todo }) => (
<h3>{todo.title}</h3>
);const AppTodoItem = ({ todo }) => (
<>
<img src={todo.img} alt={todo.title} />
<div>
<h3>{todo.title}</h3>
<p>{todo.text}</p>
</div>
</>
);<Todos todos={todos} TodoItem={HeaderTodoItem} /><Todos todos={todos} TodoItem={AppTodoItem} />
const SORT = [
[ 'без сортировки' ],
[ 'цена, по возрастанию', (a, b) => a.price - b.price ],
[ 'цена, по убыванию', (a, b) => b.price - a.price ],
[ 'год создания, по возрастанию', (a, b) => a.formed_in - b.formed_in ],
[ 'год создания, по убыванию', (a, b) => b.formed_in - a.formed_in ],
];const [ sortType, setSortType ] = useState(0);
const data = useMemo(() => {
const sortFunc = SORT[sortType][1];
return sortFunc ? [...bands].sort(sortFunc) : bands;
}, [ bands, sortType ]);<select value={sortType} onChange={e => setSortType(e.target.value)}>
{SORT.map((n, i) => <option value={i}>{n[0]}</option>)}
</select>
const [ author, setAuthor ] = useState(null);
const [ dateMin, setDateMin ] = useState(null);
const [ dateMax, setDateMax ] = useState(null);
const authors = useMemo(
() => [...new Set(articles.map(n => n.author))],
[ articles ]
);
const filteredArticles = useMemo(
() => [
[ author, n => n.author === author ],
[ dateMin, n => n.publishedAt >= dateMin ],
[ dateMax, n => n.publishedAt <= dateMax ],
].reduce((acc, n) => n[0] ? acc.filter(n[1]) : acc, articles),
[ articles, author, dateMin, dateMax ]
);<select value={author} onChange={e => setAuthor(e.target.value)}>
<option></option>
{authors.map(n => <option>{n}</option>)}
</select>
от <input type="date" value={dateMin} onChange={e => setDateMin(e.target.value)} />
до <input type="date" value={dateMax} onChange={e => setDateMax(e.target.value)} />{filteredArticles.map(n => <Card {...n} />)}
const [ autoplay, setAutoplay ] = useState(false);
const swiper = useRef();
useEffect(() => {
swiper.current.autoplay[autoplay ? 'start' : 'stop']();
}, [ autoplay ]);<input
type="checkbox"
checked={autoplay}
onChange={e => setAutoplay(e.target.checked)}
/><Swiper
onSwiper={instance => swiper.current = instance}
...
>