如何在Reactjs中将数据从子组件传递到父组件?

时间:2020-06-01 13:42:00

标签: javascript html reactjs react-hooks

我有两个组成部分,一个是孩子,另一个是父母。我有条件地翻译我的孩子部分。该代码的功能只是在您单击按钮时显示计时器,而在您单击停止计时器时将停止。这里“ Timer”是子组件,我在“ timer”组件中使用了state属性,并且我想在单击“停止计时器按钮”之前显示Timer的值。因此,如何将“定时器”状态变量值从子级传递到父级组件。

 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;

3 个答案:

答案 0 :(得分:0)

您可以将功能作为道具传递给子组件。

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

示例:

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

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

然后我调用我的子组件,并在道具中给他功能,这样他就可以修改此值:

<ChildComponent updateName={this.updateName} />
相关问题