如何用react构建单页面
react构建单页面需要使用react-router-dom库,所以我们需要先安装
npm install react-router-dom -S
下面以一个例子讲解,react构建单页面应用的方法。
react创建单页面项目并且组件传值
1、首先在app.js中配置路由,这里是通过react-router-dom这个自带的组件完成的
定义一个class类在里面进行单页面的创建,并且此文件还可以创建其他的页面以及多个单页面项目
import React, { Component } from 'react'; import { BrowserRouter as Router , Route, Switch} from 'react-router-dom' import home './components/home/home.js' class App extends Component { render() { return ( <Router> <Switch> <Route strict path="/xxx/home" component={home} /> </Switch> </Router> ) } }
2、然后在home.js文件中
主要是通过Router组件进项渲染,
在渲染的过程中, 如果要给子组件传值,必须要写成render方法渲染子组件才可以正确传值
<Route strict path="/pxr/home/search" render={() => { return <Search list={this.state.searchList}></Search> }} />
组件传值
如果要由子组件给父组件传值 , 同样也需要写成render方法渲染, 然后在子组件标签上添加一个方法,在子组件中通过this.props.方法名()触发
// 父组件 <Route strict path="/pxr/home/home" render={() => { return <HomePage getChildMsg={this.handleMsg} /> }} /> // 子组件 this.props.getChildMsg(item)
下面是全部代码, 希望对大家有帮助
import React, { Component } from 'react' import search from '../images/pxr3.webp' import { BrowserRouter as Router , Route, Link} from 'react-router-dom' import HomePage from './homePage' import SmallLoan from './SmallLoan' import Search from './Search' import DistailPage from './DistailPage' import { message } from 'antd'; class Mouth extends Component { constructor (props) { super (props) this.state = { disName: '', search: '', searchList: [] } } componentWillMount () {} componentWillReceiveProps (newProps) {} // 设置搜索值 setSearch = (e) => {} // 搜索功能 toSearch = async (e) => {} // 重置种类标签 backHome = () => {} // 设置种类标签 handleMsg = (msg) => {} render () { return ( <div className='mouth'> <Router> <div> <div className="mouth_head"> <div className="mouth_img"> <Link to="/pxr/home/home" onClick={this.backHome}> <img src={require('../images/logo1.webp')} alt=""/></Link> <span >{this.state.disName}</span> </div> <div className="mouth_inp"> <input style={img1} type="text" value={this.state.search} onChange={this.setSearch} placeholder="请输入搜索信息" /> <Link to="/pxr/home/search" onClick={(e)=>this.toSearch(e)} > <button>搜 索</button></Link> </div> </div> <Route strict path="/pxr/home/home" render={() => { return <HomePage getChildMsg={this.handleMsg} /> }} /> <Route strict path="/pxr/home/small" component={SmallLoan} /> <Route strict path="/pxr/home/search" render={() => { return <Search list={this.state.searchList}></Search> }} /> <Route strict path="/pxr/home/distail" component={DistailPage} /> </div> </Router> </div> ) } } export default Mouth
本文来自React答疑栏目,欢迎学习!
以上就是如何用react构建单页面的详细内容,更多请关注易知道|edz.cc其它相关文章!