我创建了两个组件App
和leftBar
。我在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 {}
}
}
有人指出这背后的问题是什么。我想在多个组件中使用道具。
答案 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} />
)
}