首页 > 其他 > 详细

react 使用react-router-dom 在Route对象上component 参数接收的是一个方法而非一个对象

时间:2019-09-07 15:15:11      阅读:99      评论:0      收藏:0      [点我收藏+]

其实对于jsx语法 一直觉的它有点清晰都不是很好,js和html混在一起有点不伦不类的样子,以下是我在使用react中遇到的一个很奇葩的事情

假定你定义了一个component Mine

 1 import React from ‘react‘;
 2 
 3 class Mine extends React.Component {
 4     constructor(peops) {
 5         super();
 6     }
 7 
 8     render() {
 9         console.log(‘mine‘, this);
10         return (
11             <div>
12                 <div className=‘head‘>
13                     <span>mine</span>
14                 </div>
15             </div>
16         )
17     }
18 }
19 
20 export {Mine}

 

然后你在另一个组件上引用 

import React from ‘react‘
import {Mine} from "../mine/mine";

class San extends React.Component {
    constructor(props) {
        super();
        this.state = {
            name: ‘第2个页面‘
        }
    }

    componentDidMount() {
        console.log(typeof <Mine/>)//打印
        console.log(typeof Mine) //打印
    }

    render() {
        return (
            <div id={‘san‘}>
                {this.state.name}
            </div>
        )
    }
}

export {San}

你会发现第一个<Mine/>输出的是一个对象 而Mine输出的是一个方法 而在react-router-dom中使用

return (
            <HashRouter>
                <Switch>
                    <Route exact path={‘/‘} component={Mine}/> //没有问题
                    <Route exact path={‘/‘} component={<Mine/>}/> //报错
                    <Route exact path={‘/mine2‘} component={() => Mine;
                    }/> //报错
                    <Route exact path={‘/mine2‘} component={() => <Mine/>;
                    }/> //没有问题
                    <Route exact path={‘/mine2‘} component={() => new Mine();
                    }/> //没有问题
</Switch> </HashRouter> )

 其原因就component 接收的是一个方法而不是一个对象 而这个方法返回的值必须是react组件; 

react 使用react-router-dom 在Route对象上component 参数接收的是一个方法而非一个对象

原文:https://www.cnblogs.com/wrhbk/p/11480432.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!