window使用 create-react-app 脚手架工具搭建 React 开发环境:https://blog.csdn.net/buyaopingbixiazai/article/details/83104853
模拟环境:在app.js配置路由,点击menu1跳转到menu1,点击menu2跳转到menu2
1.首先npm安装react-router-dom
安装步骤:
1)打开cmd.
2) 进入到利用脚手架工具下载的文件夹(脚手架工具快速创建项目)
3)使用命令: npm install react-router-dom
4)启动项目,命令:npm start
2.在app.js里面配置。
1)导入需要的文件
2)加上可以改变url的代码,比如<div><Link to="/Menu_1">Menu_1</Link></div> 或者直接用a标签
3)加上路由
app.js全部代码如下:
import React from 'react';
import './App.css';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
import Menu_1 from './Menu_1.js';
import Menu_2 from './Menu_2.js';
class App extends React.Component{
render(){
return (
<Router >
<div>
<div><Link to="/Menu_1">Menu_1</Link></div>
<div><Link to="/Menu_2">Menu_2</Link></div>
<div>
<Route path="/Menu_1" component={Menu_1} />
<Route path="/Menu_2" component={Menu_2} />
</div>
</div>
</Router>
)
}
}
export default App
要跳转到的页面menu1.js和menu2.js
menu1.js:
/**
* 菜单的组件
*/
import React, { Component } from 'react';
class Menu_1 extends React.Component {
render() {
return (
<div >
<div>我是menu1</div>
</div>
);
}
}
export default Menu_1;
menu2.js:
import React, { Component } from 'react';
class Menu2 extends React.Component {
/**
* 初始化
* @param {*} props
*/
constructor(props){
super(props);
this.state = {
inputValue : ''
}
}
/**
* 弹框
*/
handleBtnClick(){
if(this.state.inputValue == ''){
alert("输入为空")
}else{
alert(this.state.inputValue)
}
}
/**
* input值
* @param {*} e
*/
handleInputChange(e){
this.setState({
inputValue: e.target.value
})
}
render() {
return (
<div >
<div>我是menu2</div>
<div>
<input value={this.state.inputValue} onChange={this.handleInputChange.bind(this)}/>
<button onClick={this.handleBtnClick.bind(this)}>弹出test1消息</button>
</div>
<div>
<input value={this.state.inputValue} onChange={this.handleInputChange.bind(this)}/>
<button onClick={this.handleBtnClick.bind(this)}>弹出test2消息</button>
</div>
<div>
<input value={this.state.inputValue} onChange={this.handleInputChange.bind(this)}/>
<button onClick={this.handleBtnClick.bind(this)}>弹出test3消息</button>
</div>
</div>
);
}
}
export default Menu2;
程序入口index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<App />,
document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
测试:主页出现两个链接,点击链接分别打开不同的页面
主页:
点击menu1:
点击menu2:
把这三个文件全部拿下来就可以运行