栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

React Router和this.props.children-如何将状态传递给this.props.children

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

React Router和this.props.children-如何将状态传递给this.props.children

这个问题归结为, 您如何将道具传递给孩子?

2018年6月答案

当今的技术:

  • 反应16+
  • 反应路由器4:
    react-router-dom
  • 来自官方文档的渲染道具

假设一些有状态组件:

import React from 'react'import { BrowserRouter, Route } from 'react-router-dom'// some component you madeimport Title from './Title'class App extends React.Component {  // this.state  state = { title: 'foo' }  // this.render  render() {    return (      <BrowserRouter>        // when the url is `/test` run this Route's render function:        <Route path="/:foobar" render={          // argument is props passed from `<Route /`>          routeProps => // render Title component <Title    // pass this.state values   title={this.state.title}   // pass routeProps values (url stuff)   page={routeProps.match.params.foobar} // "test" />        } />      </BrowserRouter>    )  }}

这是有效的,因为 this.props.children 是一个函数:

// "smart" component aka "container"class App extends React.Component {  state = { foo: 'bar' }  render() {    return this.props.children(this.state.foo)  }}// "dumb" component aka "presentational"const Title = () => (  <App>    {title => <h1>{title}</h1>}  </App>)

在presandbox上的例子

我以前不再推荐的老式答案:

使用几个React帮助器方法,您可以添加状态,道具等

this.props.children

render: function() {  var children = React.Children.map(this.props.children, function (child) {    return React.cloneElement(child, {      foo: this.state.foo    })  })  return <div>{children}</div>}

然后,您的子组件可以通过props访问它

this.props.foo



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636448.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号