我创建了一个倒数计时器组件,并且在该组件附近有一个Button
我想当用户单击此按钮时,重置计时器
为此,我应该更改子状态
我找到了从孩子那里改变父母身份的解决方案,但是我没有找到解决方案
可以用ref解决吗?(我的计时器组件是功能组件)
解决方案是转发React ref转发:此博客将描述更多:https : //medium.com/javascript-in-plain-english/react-refs-both-class-and-functional-components-76b7bce487b8
import React, { useState } from "react";
import "./styles.css";
class ChildClass extends React.Component {
constructor(props) {
super(props);
this.state = {
timer: 100
};
this.resetTimer = this.resetTimer.bind(this);
}
resetTimer() {
this.setState({
timer: 0
});
}
render() {
let { timer } = this.state;
return <span>{timer}</span>;
}
}
const ChildFunction = React.forwardRef((props, ref) => {
const [timer, setTimer] = useState(100);
const resetTimer = () => {
setTimer(0);
};
React.useImperativeHandle(ref, ()=>({
resetTimer
}));
return <span>{timer}</span>;
});
export default function App() {
let childClassRef = React.createRef(null);
let childFuncRef = React.createRef(null);
const resetClassTimer = () => {
childClassRef.current.resetTimer();
};
const resetFuncTimer = () => {
childFuncRef.current.resetTimer();
};
return (
<div className="App">
<ChildClass ref={childClassRef} />
<button onClick={resetClassTimer}>Reset</button>
<br/>
<ChildFunction ref={childFuncRef} />
<button onClick={resetFuncTimer}>Reset</button>
</div>
);
}
我添加了带有类组件和功能组件的ref转发。React.js和React本机都是一样的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句