cari

Rumah  >  Soal Jawab  >  teks badan

javascript - React router 组件名如何通过遍历得到?

想法是这样的,通过定义一个对象/数组来存导航部分的数据。

1

2

3

4

5

<code>data = [

    {title: "home", url: "home"},

    {title: "about", url: "about"},

    {title: "blog", url: "blog"},

]</code>

列表的组件写的是没有问题的,下面是Router部分,简写了,获取URL是没有问题的。

1

2

3

4

5

6

7

<code>data.map(function (item, index, arr) {

    // 组件名首字母大写

    var com_name = item.url.charAt(0).toUpperCase() + item.url.substr(1);

    return (

        <Route path={item.url} component={!!!!此处有问题!!!!!}></Route>

    )

})</code>

对于问题部分的代码:

1

2

3

4

5

6

7

8

9

10

11

12

<code>// 想要的情况

<Route component={Home}></Route>

 

// 如果这么写

<Route component={com_name}></Route>

// 相当于

<Route component={"Home"}></Route>

// 这种情况不匹配

 

// 如果这么写

<Route component={eval(com_name)}></Route>

// DEBUG显示未定义</code>

想说的是,究竟应该怎么写?

巴扎黑巴扎黑2898 hari yang lalu148

membalas semua(2)saya akan balas

  • 天蓬老师

    天蓬老师2017-04-10 16:50:42

    试一下这样<Route component={require("Home的路径")}></Route>

    balas
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 16:50:42

    React Router有不用jsx的写法

    可以这样写

    1

    2

    3

    4

    5

    6

    7

    <code>data.map(function (item, index, arr) {

        // 组件名首字母大写

        var com_name = item.url.charAt(0).toUpperCase() + item.url.substr(1);

        return (

            React.createElement(DefaultRoute, {name: "index", path: item.url, component: com_name})

        )

    })</code>

    也可以使用React工厂函数

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    <code>var Route = React.createFactory(Router.Route);

    data.map(function (item, index, arr) {

        // 组件名首字母大写

        var com_name = item.url.charAt(0).toUpperCase() + item.url.substr(1);

        return (

            Route({

                name: "index",

                path: item.url,

                component: com_name

            });

        )

    })</code>

    再简单一点,直接将路由数据按规定的格式定义好,丢给Router就ok

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    <code>const data = [

        {

            path: '/',

            component: Home,

            childRoutes:[

                {path: "home", component: Home},

                {path: "about", component: About},

                {path: "blog", component: Blog},

            ]

        }

    ];

    render(<Router routes={data} />, document.body)</code>

    balas
    0
  • Batalbalas