我创建了一个倒计时器组件
我在这个组件附近有一个按钮
我希望当用户单击此按钮时重置计时器
为此我应该改变子状态
我找到了从孩子那里改变父母状态的解决方案
但我找不到解决方案
可以用ref解决吗?
(我的计时器组件是一个功能组件)
React ref 转发是解决方案:
这篇博客将描述更多:https://medium.com/javascript-in-plain-english/react-refs-both-class-and-function-components-76b7bce487b8 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>
);
}
我添加了类组件和功能组件的引用转发。
React.js 和 React Native 都是一样的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)