使用react创建单页面项目

使用react创建单页面项目

 

react创建单页面项目并且组件传值
首先在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>
)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
然后在home.js文件中
主要是通过Router组件进项渲染,
在渲染的过程中, 如果要给子组件传值,必须要写成render方法渲染子组件才可以正确传值
<Route strict path="/pxr/home/search" render={() => {
return <Search list={this.state.searchList}></Search>
}} />
1
2
3
组件传值
如果要由子组件给父组件传值 , 同样也需要写成render方法渲染, 然后在子组件标签上添加一个方法,在子组件中通过this.props.方法名()触发
// 父组件
<Route strict path="/pxr/home/home" render={() => {
return <HomePage getChildMsg={this.handleMsg} />
}} />

// 子组件
this.props.getChildMsg(item)
1
2
3
4
5
6
7
下面是全部代码, 希望对大家有帮助
import React, { Component } from 'react'
import search from '../images/pxr3.png'
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.png')} 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

原文链接:https://blog.csdn.net/weixin_45289067/article/details/95048225

posted @ 2020-05-08 09:12  威武的大萝卜  阅读(853)  评论(0编辑  收藏  举报