react-route不用redux怎么给组件传参呢?

普通组件这样传参

class Home extends Component {


    constructor(props) {

        super(props)

    }


    doSomething() {

        

    }


    render() {

        return (

            <div>

                <Child onDoSomething={this.doSomething} />

            </div>

        );

    }

}


如果组件被弄到路由里面了,那Home组件怎么把doSomething传递给Child调用呢?(redux我知道,想知道不用redux,怎么传递)

class Home extends Component {


    constructor(props) {

        super(props)

    }


    doSomething() {


    }


    render() {

        return (

            <div>

                <Route path="/child" component={Child} />

            </div>

        );

    }

}


海绵宝宝撒
浏览 575回答 2
2回答

拉风的咖菲猫

可以在Route上边用render的方式加载子组件,这样就可以传递你的这些函数之类的了。<Route render={props => (&nbsp;&nbsp; &nbsp; &nbsp; <Component onDoSomething={this.doSomething}/>&nbsp; )}/>

皈依舞

好的,解决了class Home extends Component {&nbsp; &nbsp; constructor(props) {&nbsp; &nbsp; &nbsp; &nbsp; super(props)&nbsp; &nbsp; }&nbsp; &nbsp; doSomething() {&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Auth path='/user' component={User} onDoSomething={this.doSomething} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }}class Auth extends Component {&nbsp; &nbsp; constructor(props) {&nbsp; &nbsp; &nbsp; &nbsp; super(props)&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; let { component: Part, ...rest } = this.props&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route {...rest} render={(props) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 这里的rest就把onDoSomething穿都给User组件了<Part {...rest} {...props} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; true ? <Part {...rest} {...props} /> : <Redirect to={{pathname: '/login', state: {from: props.location }}} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript