![](/img/trans.png)
[英]How to change functional component's state from another component that is not a parent or a child?
[英]How to change the child state component from parent in functional component
我创建了一个倒数计时器组件,并且在该组件附近有一个按钮
我想当用户点击这个按钮时,重置计时器
为此我应该改变孩子 state
我找到了从孩子那里更改父母 state 的解决方案,但我没有找到解决方案
可以用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>
);
}
我添加了带有 class 组件和功能组件的 ref 转发。 React.js 和 React native 都是一样的。
您所要做的就是将道具传递给孩子,让父母更新 state
cont Parent = (props) =>{
const [timer, setTimer] = useState(100)
cont resetTimer = () => {
setTimer(0)
}
render(){
return <span>{timer}</span>
<Child timer={timer}>
}
}
在孩子
cont Child = (props) =>{
const timer= props.timer;
render(){
return <span>I am child with time {timer}</span>
}
}
一种方法是,如果你想从子组件更改父 state 那么你应该通过道具从子组件调用父 function
cont Child = (props) =>{
render(){
return (<span>I am child with time {props.timer}</span>
<Button onClick = {props.resetTimer}></Button>
)
}
}
cont Parent = (props) =>{
const [timer, setTimer] = useState(100)
cont resetTimer = () => {
setTimer(0)
}
render(){
return <span>{timer}</span>
<Child timer={timer} setTimer={setTimer}>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.