![](/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.