组件道具 returns 空反应 js

component props returns empty react js

我创建了两个组件 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 {}
    }
}

有人指出这背后的问题是什么。我想在多个组件中使用道具。

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

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

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

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

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

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

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