我有这样的路由结构:
<Route path="/master" component={MasterPageLayout}> <IndexRoute path="/master/products" component={ProductsPage}/> <Route path="/master/customer/:id" component={CustomerDetailsPage}/> <Route path="/master/product/:id" component={ProductDetailsPage}/> <Route path="/master/price-table" component={PriceTablePage} /> </Route> <Route path="/poc" component={DistribuitorPageLayout}> <IndexRoute path="/poc/inventory" component={InventoryPage}/> </Route>
在“ MasterPageLayout我的标题”和“我的侧面props.children菜单”(在他上方的所有嵌套路线通用)的内部,这些菜单结构内均呈现,但我的标题为每条路线都有一个特定的文本。如何将文本(也许还有其他一些数据)从孩子传递给父亲?
MasterPageLayout
props.children
将数据传递回树通常是通过回调处理的。因为您只需要获取一次值,我建议您使用一种安装生命周期方法来调用回调。
正如您所标记的react- redux,我将为React和Redux提供示例。我不认为基本的React示例实际上适合您的情况,因为您正在渲染props.children,这使得传递回调更加困难,但是我将其留在答案中,以防它对其他人有用。redux示例应适用于您的问题。
react- redux
您可以将回调传递给子级,该子级在渲染时使用的组件状态中设置一个值
class Child extends React.Component { componentWillMount() { this.props.setText("for example") } render() { return ( <div>whatever</div> ) } } class Parent extends React.Component { render() { return ( <div> <Child setText={(text) => this.setState({text})} /> {this.state.text} </div> ) } }
您可以在挂载子项时分派一个操作来设置文本,该操作会在商店中设置一个值以在父项中呈现,例如
class ChildView extends React.Component { componentWillMount() { this.props.setText("for example") } render() { return ( <div>whatever</div> ) } } const mapDispatchToProps = (dispatch) => { return { setText: (text) => dispatch(setParentText(text)) } } const Child = connect(null, mapDispatchToProps)(ChildView) const ParentView = ({ text }) => { return ( <div> <Child /> {text} </div> ) } const mapStateToProps = (state) => { return { text: state.parent.text } } const Parent = connect(mapStateToProps)(ParentView)
我不会担心显示动作创建者和减速器/商店设置。如果您使用的是redux,则应该能够弄清楚这一点。
如果Parent不直接渲染Child(无论是通过渲染props.children还是引入额外的图层),此方法也将起作用。实际上,只要这两种方法都在同一页面上呈现,那么使用这种方法Parent就完全不需要成为祖先Child。
Parent
Child