1.App.js 要在app.js文件里挂在路由
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Time from './Time';
import Conter from './Conter';
import './App.css';
function App() {
return (
<Router>
<Route exact path="/" component={Time} />
<Route path="/Conter" component={Conter} />
</Router>
);
}
export default App;
2.Time.js,这个是要传值的页面
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './time.css';
import { useHistory } from 'react-router-dom';
export const Time = () => {
const history = useHistory();
const handleClick = (item) => {
history.push({
pathname: "/Conter",
state: { title: `${item}` }
});
};
const [data, setData] = useState(null);
useEffect(() => {
axios.get('http://127.0.0.1/api/get?mane=zhangsan&age=20')
.then(response => {
setData(response.data);
console.log(data);
})
.catch(error => {
console.log(error);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const listTitle = ['水果', '蔬菜', '饮料', '动物', '植物', '职业'];
const listContent = {
水果: [
'苹果',
'香蕉',
'橘子',
'鸭梨',
'桔子',
'梨子',
'西瓜',
'橙子',
'柚子',
'葡萄',
'甘蔗',
'桃子',
'杨桃',
'石榴'
],
蔬菜: [
'小青菜',
'胡萝卜',
'豆角',
'辣椒',
'大蒜',
'娃娃菜',
'黄瓜',
'冬菇',
'冬瓜',
'南瓜',
'大白菜',
'芹菜',
'扁豆',
'四季豆'
],
植物: [
'柏树',
'松树',
'杨树',
'柳树',
'牡丹',
'玫瑰',
'百合',
'桂花',
'香樟树',
'月季',
'银杏树',
'六月雪',
'杜鹃',
'三角梅'
],
饮料: [
'冰红茶',
'绿茶',
'脉动',
'可口可乐',
'百事可乐',
'茶π',
'茉莉花茶',
'柠檬水',
'蜂蜜柚子',
'酸梅汤',
'水蜜桃',
'冰糖雪梨',
'金桔柠檬'
],
动物: [
'狗',
'猫',
'猪',
'老虎',
'狮子',
'狼',
'鸡',
'牛',
'猴子',
'马',
'熊猫',
'兔子',
'鸭'
],
职业: [
'工人',
'农民',
'IT',
'警察',
'消防员',
'售货员',
'收银员',
'推销员',
'老师',
'教练',
'学生',
'司机',
'售票员'
]
};
const [selectedTitle, setSelectedTitle] = useState(listTitle[0]);
const title = listTitle.map((item) => (
<li
className={selectedTitle === item ? 'active' : ''}
key={item}
onClick={() => setSelectedTitle(item)}
>
{item}
</li>
));
const content = listContent[selectedTitle]?.map((item) => (
<li key={item} onClick={() => handleClick(item)}>
{item}
</li>
));
return (
<div className='box'>
<div className='lsitTitle'>
<ul>{title}</ul>
</div>
<div className='lsitConter'>
<ul>{content}</ul>
</div>
</div>
);
};
export default Time;
(1)简单写了一个tab切换
3.Conter.js,接收值得页面
import React from 'react'
export const Conter = (props) => {
const title = props.location.state ? props.location.state.title : null;
console.log(title);
return (
<div>Received Value: {title}</div>
)
}
export default Conter;
仅供与参考;