![](/img/trans.png)
[英]Can I pass a 'const' variable from one component to another in ReactJS?
[英]Data from one component into another through the const?
我是新的反應js,我試圖從組件A獲取數據/狀態到組件B,我知道這聽起來很容易,但我嘗試了很多例子,但無法做到。 問題有點不同:我嘗試了createContenxt
export const AContext = React.createContext('test');
class A extends Component {
constructor(props){
this.state = { id: this.props.aStore.id()}}
if login success go to component C:
<AContext.Provider value="test">
<Route render={(props) => <C {...props} id={this.state} />} />
</AContext.Provider>
class C extends Component {
<Sidebar routes={dashboard}>
const dashboard = {path: "/b",
sidebarName: "b",
navbarName: "b",
icon: IconDashboard,
component: B}
import {AContext} from './A';
class B extends Component {
static contextType = AContext;
render(){ console.log(this.context)} //=> empty object
以下是代碼如何工作的想法,現在我必須將id轉換為組件B,我設法通過C傳遞它但是如何將它傳遞給const儀表板和組件B?
最好像這樣構建你的React頁面:
return(
<div>
{ shouldGoHere ? <SomeComponent props={this.state.propsGoHere} /> : null }
{ shouldGoThere ? <OtherComponent props={this.state.propsGoThere} /> : null }
</div>
)
但是使用React Router會更好
import { BrowserRouter, Route } from 'react-router-dom'
...
return(
<div>
<BrowserRouter>
<Route exact to="/" component={HomeComponent} props={this.state.propsGoHere} />
<Route exact to="/otherComponent" component={OtherComponent} props={this.state.MorePropsHere} />
</BrowserRouter>
</div>
)
使用此代碼段,您可以輕松地操縱哪些數據進入哪個組件,並且還可以更輕松地瀏覽您的應用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.