【问题标题】:How can I pass data from child component to parent component in Reactjs? [duplicate]如何在 Reactjs 中将数据从子组件传递到父组件? [复制]
【发布时间】:2020-09-19 20:03:24
【问题描述】:

我有两个组件,一个是子组件,另一个是父组件。我有条件地渲染我的子组件。此代码的功能是当您单击按钮时将显示计时器,当您单击停止时计时器将停止。这里“定时器”是子组件,我在“定时器”组件中使用了状态属性,我想在单击“停止定时器按钮”之前显示定时器的值。那么如何将“计时器”状态变量值从子组件传递给父组件。

 const[time,setTime]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }
 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer/>:null}

这是父组件,以下代码用于“计时器”组件。

import React,{useEffect,useState} from 'react';
const Timer = () => {  
    const[timer,setTimer]=useState(0);
    useEffect(()=>{
        setTimeout(()=>{
            setTimer(prevTime=>prevTime+1);
        },100)
    },[timer])
    let style={
        position:"absolute",
        height:"100px",
        weight:"200px",
        backgroundColor:"red",
        zIndex:"1"
    }
    const handleStopTime=()=>{
        console.log(timer);
        setTimer(0);
    }
    return (
        <div style={style}>
            <h1>{timer}</h1>
        </div>
      );
}

export default Timer;

【问题讨论】:

  • 不,但以下答案确实如此。

标签: javascript html reactjs react-hooks


【解决方案1】:

您可以将函数作为道具传递给子组件。

const Parent = () => {
    const [dataState, updateState] = useState('');

    const handler = (data) => {
        updateState(data)
    }

    return (
         <Child someHandlerProp={handler}/>
    )
}

const Child = (props) => {
    return (
        <button onClick={() => props.someHandlerProp('some data')}>Button</button>
    )
}

【讨论】:

    【解决方案2】:

    您可以像这样将函数传递给您的计时器:

    const[time,setTime]=useState(0);
    const[timerValue,setTimerValue]=useState(0);
     const handleStart=()=>{
        setTime(true);
     }
    const handleStop=()=>{
        setTime(false);
     }
    
     .....
    <button onClick={handleStart}>Start StopWatch</button>
    <button onClick={handleStop}>Stop StopWatch</button>
    {time?<Timer updateTimerValue={setTimerValue}/>:null}
    
    

    在你的计时器之后,你可以使用这个道具来更新父状态:

    const handleStopTime=()=>{
            console.log(timer);
            props.updateTimer(timer)
            setTimer(0);
        }
    

    【讨论】:

    • 您的答案不够清楚,但我使用以下答案之一解决了它。
    【解决方案3】:

    您可以将函数传递给子组件,该子组件会更新父组件中的值。

    例子:

    我的父母有一个变量:name; 所以我在父组件中设置了一个函数:

    updateName = (newValue) => {
        this.setState({
                    name: newValue,
                });
        } 
    

    然后我调用我的子组件并将道具中的功能给他,所以他可以修改这个值:

    <ChildComponent updateName={this.updateName} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 2017-04-28
      相关资源
      最近更新 更多