我想在React Project中写一个Router。但是Route子级和cloneElement在版本4中不再起作用。我还没有找到演示或教程来教路由器4中如何在路由器中传递值。

有解决这个问题的想法吗?

我在Github中的项目:https://github.com/LeMueller/musicplayer-by-react/tree/dev

非常感谢。

import React, {Component} from 'react';
import Header from './commen/header.js';
import Player from './page/player.js';
import {MUSIC_LIST} from '../config/musiclist';
import MusicListUI from './page/musiclistui.js';

import {HashRouter, Switch, Route, Link} from 'react-router-dom';


class MusicApp extends Component{
    constructor(props){
        super(props);
        this.state={
            musiclist: MUSIC_LIST,
            currentMusicItem: MUSIC_LIST[0]
        }
    }

    componentDidMount(){


        $('#player').jPlayer({
            ready:function(){
                $(this).jPlayer('setMedia',{
                    mp3:'http://oj4t8z2d5.bkt.clouddn.com/%E9%AD%94%E9%AC%BC%E4%B8%AD%E7%9A%84%E5%A4%A9%E4%BD%BF.mp3'
                }).jPlayer('play');
            },
            supplied:'mp3',
            wmode: 'window'
        });


    }

    componentWillUnMount(){

    }

    render(){
        return(
            <div>
                {React.cloneElement(this.props.children, this.state)}
            </div>
        )
    }
}

export default class Root extends Component{
    render(){
        return(
            <HashRouter>
                <div>
                    <Header/>
                    <Route exact path="/" component={MusicApp}>
                        <Route exact path="/" component={Player }></Route>
                        <Route path="/list" component={MusicListUI}></Route>
                    </Route>
                </div>

            </HashRouter>
        )
    }
}

最佳答案

如果要通过组件将道具传递给组件,则可以使用渲染,例如:

<Route exact path="/" render={(props) => <Player example={ props.example } /> }></Route>

关于javascript - 将“Route children”和“cloneElement”转换为RouterV4,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46244010/

10-10 20:22