Javascript 无法从父级访问函数-从父级向子级发送道具
我有一个应用程序,它有一个导航栏,下面有一个显示所有帖子的显示屏 以下是它的设置方式:Javascript 无法从父级访问函数-从父级向子级发送道具,javascript,reactjs,Javascript,Reactjs,我有一个应用程序,它有一个导航栏,下面有一个显示所有帖子的显示屏 以下是它的设置方式: var routes = ( <Router history={createHistory()}> <Route path="/" component={App}> <Route path="/submit" component={CreatePost}/> </Route> &l
var routes = (
<Router history={createHistory()}>
<Route path="/" component={App}>
<Route path="/submit" component={CreatePost}/>
</Route>
<Route path="*" component={NotExist}/>
</Router>
)
@kirill fuchs昨天告诉我使用{this.props.children}发送属性。然而,当我检查react控制台时,我看到道具是空的。但,我知道它在做一些事情,因为若我去掉了{this.props.children},那个么点击New就什么也做不了。但当我把它放回去时,它会重定向到表单
此外,当我在表单中单击submit时,它会说this.props.addToPosts不是一个函数,因为props是空的
有人能帮帮我吗?听起来你想把道具传给孩子们。您可以使用以下方法进行此操作:
{React.cloneElement(this.props.children,{addToPosts:this.addPostToPosts,posts:this.state.posts})}
这将把一个道具传递到
CreatePost
组件中,当按下submit按钮时,您可以调用该组件。在导航栏中添加新代码
render : function() {
//<CreatePost addPostToPosts={this.addPostToPosts} posts={this.state.posts}/>
return (
<div>
<NavigationBar/>
{this.props.children}
<DisplayPosts postData={this.state.posts} />
</div>
)
}