ReactJS-将道具传递给子组件,但无法在子组件中访问它

时间:2019-11-15 20:08:20

标签: javascript reactjs

我正在将道具“时间”从Home.js(父)组件传递到Game.js组件(子组件) 但是我无法在Game.js文件中访问它。

Home.js

import React, {useState,Fragment} from 'react';
import {withRouter} from 'react-router-dom';
import Game from './Game';


const Home = ({history}) => {
    const [time, setTime] = useState(0);
    const [show, setShow] = useState(false);
    const handleChange = (e) => {
        setTime(e.target.value);
    }

    const handleClick = () => {
        // console.log(time); // this console is working with time value.
        setShow(!show);
        history.push('/game');
    }
    return (
    <Fragment>
        <div className="col-md-6 offset-md-3">
            <form>
                <div className="form-group">
                    <label>Select the game time</label>
                    <select className="form-control" onChange={handleChange}>
                        <option>choose time</option>
                        <option value='5'>5 second</option>
                        <option value='10'>10 second</option>
                        <option value='15'>15 second</option>
                        <option value='20'>20 second</option>
                        <option value='25'>25 second</option>
                        <option value='30'>30 second</option>
                    </select>
                </div>
                <button to='/game' onClick={() => handleClick()} className="btn btn-dark btn-lg btn-block mt-5">Start</button>
            </form>
        </div>
        { show && <Game time={time} /> }  // passing time props to Game component.
        </Fragment>
    )
}
export default withRouter(Home);

Game.js

import React from 'react';

const Game = ({time}) => {

    useEffect(()=>{
        console.log('Timer ',time);  // unable to access time props coming from Home.js 
                                     //component i.e undefined
    },[]);


    return (
        <div>
            I am the Game.js component and i am unable to access 'time' props
        </div>
    )
}
export default Game;

为什么我无法访问来自“ Home.js”文件的“时间”道具? 它应该是可访问的,并在useEffect()中赋予其安慰价值。

0 个答案:

没有答案