组件props返回空反应js

时间:2018-02-24 07:47:03

标签: javascript reactjs react-router-v4 react-router-dom

我创建了两个组件AppleftBar。我在App组件中获得Class component props。但LeftBar中的同一道具是空的。

Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Route, Switch} from 'react-router-dom';


/** Component **/
import App from './App';


ReactDOM.render(
    <BrowserRouter>
    <Switch>
        <Route path="/:folders/:actions" component={App}></Route>
    </Switch>
</BrowserRouter>, document.getElementById('app'));

App.js

import React, {Component} from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';

import LeftBar from './components/left-bar';

class App extends Component {
 constructor(props){
    super(props);
    console.log(this.props); //Returns the object
  }

render(){
   return (
     <LeftBar />
   )
  }
}

LeftBar.js

class LeftBar extends Component{
  constructor(props) {
        super(props);
        this.state = {
            leftBar: ["sarath"]
        }
        console.log(this.props); //this returns empty object {}
    }
}
有人指出这背后的问题是什么。我想在多个组件中使用道具。

2 个答案:

答案 0 :(得分:1)

因为您没有在<LeftBar />上分配任何道具。

您还必须将所需的道具传递给此组件:

render(){
 return (
   <LeftBar {...this.props}/>
 )
}

答案 1 :(得分:1)

react-router不会按照您希望的方式传递道具。您需要先通过

将道具传递给App
// ...
<Route path="/:folders/:actions" component={props => <App {...this.props} />} />

然后你需要在你的子组件中传递它们。 我包含this.state,假设您要在LeftBar内使用此内容,但如果不正确,您可以删除{...this.state}

// ...
render () {
    return (
        <LeftBar 
            {...this.props} 
            {...this.state} />
    )
}