如何在功能组件中从父级更改子状态组件

IT技术 javascript reactjs react-native
2022-07-05 02:12:08

我创建了一个倒数计时器组件,并且在该组件附近有一个按钮

我想当用户点击这个按钮时,重置计时器

为此我应该改变孩子状态

我找到了从孩子更改父状态的解决方案,但我没有找到解决方案

可以用 ref 解决吗?(我的计时器组件是一个功能组件)

3个回答

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 native 都是一样的。

您所要做的就是将您的props传递给孩子以获取父母更新的状态

  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>
      }
  }

一种方法是,如果要从子组件更改父状态,则应通过props从子组件调用父函数

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}>
      }
}