zoukankan      html  css  js  c++  java
  • react 使用react-router-dom 在Route对象上component 参数接收的是一个方法而非一个对象

    其实对于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组件; 

  • 相关阅读:
    .ellipsis 超过的部分显示省略号
    js 里面上一页和下一页
    CSS让你的IE浏览器崩溃(Crash your IE)作者:雪候鸟 来源: 风雪之隅
    元素居中显示
    jquery Carousel
    tabs 选择加载
    弹出窗
    下拉广告`
    opacity
    小波分析实验: 实验1 连续小波变换
  • 原文地址:https://www.cnblogs.com/wrhbk/p/11480432.html
Copyright © 2011-2022 走看看