如何将组件回调传递给react-router中的children元素?

时间:2016-07-02 07:56:18

标签: javascript reactjs react-router react-redux

我想用一个MapBox包装我当前的路由器并传递给子MapBox回调函数:

  <Route path='/posts' component={PostsList} />
    <Route path="/posts/:id" component={Post} >
  </Route>

目前为了处理回调,我在两个组件上重复MapBox:

export default class Post extends React.Component {
  mapMoved(map) {console.log('map moved', map)}
  render() {
    const {post, posts} = this.props;
    return (
      <div>
        {post.title}
        <MapBox mapMoved={::this.mapMoved} posts={posts} />
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  post: state.post,
  posts: state.posts,
});
export default connect(mapStateToProps)(Post);

export default class PostsList extends React.Component {
  renderList() {
    const {posts} = this.props;
  }
  mapMoved(map) {console.log('map moved', map)}
  render() {
    return (
      <div>
        {::this.renderList()}
        <MapBox mapMoved={::this.mapMoved} posts={this.props.posts} />
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  posts: state.posts,
});
export default connect(mapStateToProps)(PostsList);

布局所包含的所需路线:

<Route component={Layout}>
  <Route path='/posts' component={PostsList} />
    <Route path="/posts/:id" component={Post} >
  </Route>
</Route>

所需的布局组件:

export default class Layout extends React.Component {
  mapMoved(map) {}
  render() {
    return (
      <div>
        {this.props.children} //I would like to pass mapMoved callback here
        <MapBox mapMoved={::this.mapMoved} posts={this.props.posts} />
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  posts: state.posts,
});
export default connect(mapStateToProps)(Layout);

我正在使用Redux,也许我应该通过它以某种方式传递回调函数?

1 个答案:

答案 0 :(得分:1)

您可以将道具传递给儿童,如此

export default class Layout extends React.Component {
  mapMoved(map) {}
  render() {
    return (
      <div>
        {React.cloneElement(this.props.children || <div />, {mapMoved: (map) => this.mapMoved(map)})} //I would like to pass mapMoved callback here
        <MapBox mapMoved={::this.mapMoved} posts={this.props.posts} />
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  posts: state.posts,
});

export default connect(mapStateToProps)(Layout);