我对学习React还是很陌生,而且我很难将类组件转换为功能组件。
以下是带有类组件的代码:
const copyEmail = useCallback(() => {
copy(revokeSupportEmail);
this.timer = setTimeout(_ => {
this.setState({msg: 'Some new text'}); // swap the text
this.setState({fading: false}); // fade back in
}, 500);// reset text
}, []);
render() {
const {msg, fading} = this.state;
return (
<h1 className={`${fading ? 'faded' : ''}`}>
{msg}
</h1>
);
}
这是我到目前为止尝试过的代码:
function copyEmail() {
const [timeout, setTimeout] = useState([{ text:
'Some text here'}]);
以及
function copyEmail {
const [msg: 'Some text here'] = useState(0)
const [fading: false] = useState(false)
任何帮助将不胜感激。
答案 0 :(得分:0)
关于设置状态,您可以按照自己认为合适的方式进行构造:
function copyEmail() {
const [state, setState] = useState(null)
// OR
const [state, setState] = useState({fading: false, msg: ""})
// OR
const [msg, setMsg] = useState("")
const [fading, setFading] = useState(false)
}
功能组件没有this
上下文,因此请将其删除
timer = setTimeout(_ => {
setState({fading: false, msg: 'Some text here'})
// OR
setMsg("Some text here.")
setFading(false)
}, 500);// reset text