Skip to content

Instantly share code, notes, and snippets.

@grootfish
Last active June 4, 2020 11:35
Show Gist options
  • Save grootfish/9f9198063a2fbe4b751af4a653837e0b to your computer and use it in GitHub Desktop.
Save grootfish/9f9198063a2fbe4b751af4a653837e0b to your computer and use it in GitHub Desktop.
JS Snippets
// 受控组件
function ControlledInput({
callback,
type = 'text',
disabled = false,
readOnly = false,
defaultValue,
placeholder = ''
}) {
const [value, setValue] = React.useState(defaultValue);
React.useEffect(() => {
callback(value);
}, [value]);
return (
<input
defaultValue={defaultValue}
type={type}
disabled={disabled}
readOnly={readOnly}
placeholder={placeholder}
onChange={({ target: { value } }) => setValue(value)}
/>
);
}
function CountDown({ hours = 0, minutes = 0, seconds = 0 }) {
const [paused, setPaused] = React.useState(false);
const [over, setOver] = React.useState(false);
const [time, setTime] = React.useState({
hours: parseInt(hours),
minutes: parseInt(minutes),
seconds: parseInt(seconds)
});
const tick = () => {
if (paused || over) return;
if (time.hours == 0 && time.minutes == 0 && time.seconds == 0) setOver(true);
else if (time.minutes == 0 && time.seconds == 0)
setTime({
hours: time.hours - 1,
minutes: 59,
seconds: 59
});
else if (time.seconds == 0)
setTime({
hours: time.hours,
minutes: time.minutes - 1,
seconds: 59
});
else
setTime({
hours: time.hours,
minutes: time.minutes,
seconds: time.seconds - 1
});
};
const reset = () => {
setTime({
hours: parseInt(hours),
minutes: parseInt(minutes),
seconds: parseInt(seconds)
});
setPaused(false);
setOver(false);
};
React.useEffect(() => {
let timerID = setInterval(() => tick(), 1000);
return () => clearInterval(timerID);
});
return (
<div>
<p>{`${time.hours.toString().padStart(2, '0')}:${time.minutes
.toString()
.padStart(2, '0')}:${time.seconds.toString().padStart(2, '0')}`}</p>
<div>{over ? "Time's up!" : ''}</div>
<button onClick={() => setPaused(!paused)}>{paused ? 'Resume' : 'Pause'}</button>
<button onClick={() => reset()}>Restart</button>
</div>
);
}
# 深拷贝
function extend(source,target=new weakMap()){
if(typeof source !== 'object'){
return source;
}
let targetClone = Array.isArray(source) ? [] : {};
if (target.get(source)) {
return target.get(source);
}
target.set(source, targetClone);
for(key in source){
targetClone[key] = extend(source[key])
}
return targetClone
}
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import axios from 'axios';
function SearchResults() {
const [data, setData] = useState({ hits: [] });
const [query, setQuery] = useState('react');
useEffect(() => {
let ignore = false;
async function fetchData() {
const result = await axios('https://hn.algolia.com/api/v1/search?query=' + query);
if (!ignore) setData(result.data);
}
fetchData();
return () => { ignore = true; }
}, [query]);
return (
<div>
<input value={query} onChange={e => setQuery(e.target.value)} />
<ul>
{data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
<div/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<SearchResults />, rootElement);
function LimitedTextarea({ rows, cols, value, limit }) {
const [content, setContent] = React.useState(value);
const setFormattedContent = text => {
text.length > limit ? setContent(text.slice(0, limit)) : setContent(text);
};
React.useEffect(() => {
setFormattedContent(content);
}, []);
return (
<div>
<textarea
rows={rows}
cols={cols}
onChange={event => setFormattedContent(event.target.value)}
value={content}
/>
<p>
{content.length}/{limit}
</p>
</div>
);
}
const useClickInside = (ref, callback) => {
const handleClick = e => {
if (ref.current && ref.current.contains(e.target)) {
callback();
}
};
React.useEffect(() => {
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
});
};
const useClickOutside = (ref, callback) => {
const handleClick = e => {
if (ref.current && !ref.current.contains(e.target)) {
callback();
}
};
React.useEffect(() => {
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
});
};
const useInterval = (callback, delay) => {
const savedCallback = React.useRef();
React.useEffect(() => {
savedCallback.current = callback;
}, [callback]);
React.useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};
const usePrevious = value => {
const ref = React.useRef();
React.useEffect(() => {
ref.current = value;
});
return ref.current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment