首页 > 解决方案 > 使用 React 路由器时将 props 传递给另一个组件下面的进一步说明

问题描述

下面是我的组件的代码,Home其中我有这个money变量,我想将它作为道具传递给我,<Play/>但我无法这样做。

import React,{useState} from 'react';
import {Container,Row,Col,Button} from 'react-bootstrap';
import { useHistory } from 'react-router-dom';
import './Home.css';

function Home(props){
    
    const history = useHistory();
    const initValues = ['50 Millions','100 Millions','1 Billion','2 Billions','5 Billions','10 Billions',
'50 Billions','100 Billions','500 Billions'];
    
    const [values,setValues] = useState(initValues);
    const [money,setMoney] = useState(0);
    function handleSubmit(e){
        const {name} = e.target;
      
        if ( name === '50 Millions'){ 
            setMoney( numberWithCommas(50000000) ) }
        if ( name === '100 Millions'){ 
            setMoney(numberWithCommas(100000000)); }
        if ( name === '1 Billions'){
             setMoney(numberWithCommas(1000000000)); }
        if ( name === '2 Billions'){
             setMoney(numberWithCommas(2000000000)); }
        if ( name === '5 Billions'){
             setMoney(numberWithCommas(5000000000)); }
        if ( name === '10 Billions'){
             setMoney(numberWithCommas(10000000000)); }
        if ( name === '50 Billions'){
             setMoney(numberWithCommas(50000000000)); }
        if ( name === '100 Billions'){
             setMoney(numberWithCommas(100000000000)); }
        if ( name === '500 Billions'){
             setMoney(numberWithCommas(500000000000)); }

     history.push('/play');


    }
  
    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      }


  return  <Container className='justify-content-center'>
      <Row className='justify-content-center'>
      <div className="outer-div">
        <h4 className='prompt-intro'> Choose How much money do you want to have.</h4>
        
        {
            values.map( (value,i) => {
                return <Button className='money-btn btn-lg' variant='primary'  type='submit' onClick={handleSubmit} name={value}>{value}</Button>
            })
        }
   
    </div>
    </Row>
     </Container>
    

    
}

export default Home;

标签: javascriptreactjsreact-router

解决方案


只需<Play money={money} />Home组件中使用,并在Play组件中通过props.money.


推荐阅读