javascript - 使用 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;
解决方案
只需<Play money={money} />
在Home
组件中使用,并在Play
组件中通过props.money
.
推荐阅读
- php - 如何制作返回与需要在其中查找值的数组关联的键名的函数?
- node.js - heroku DATABASE_URL 在 nodejs 应用程序中未定义
- javascript - Javascript:如何从原型管理转移到类的概念?
- ios - 如何在 react-native 项目中保存 info.plist 中的更改
- amazon-web-services - 是否可以将 VM 快照映像从 GCP 共享到 AWS,反之亦然?
- qemu - QEMU 上的 Microblaze 不产生串行输出
- git - 远程删除文件夹但不是本地git
- excel - 如果满足某些条件并将结果输入另一个工作簿,则计算行数
- c# - C# PInvoke 我无法使用 CreateFile 打开卷
- python - 运行从不同位置导入另一个 python 脚本的 Python 脚本