【问题标题】:React: Are props objects passed automatically to children components or does there always exist some default props?反应:道具对象是自动传递给子组件还是总是存在一些默认道具?
【发布时间】:2019-12-10 02:54:08
【问题描述】:

是否存在一些总是从父组件向下传递给子组件的默认 props 对象?

我知道可以将 props 从父组件传递给某些子组件,例如:

<div>
<ChildComponent color="blue" otherProp=false />
</div>

并通过props.colorprops.otherProp 在子组件中访问它们... 但是如果我不为我的子组件创建 props,是否仍然存在一些默认的 props 对象(或者可能是一些 props 元对象)以及该子组件的附加信息?

例如,我看到一些匹配对象由 React-router 库自动创建并传递给匹配某些路由路径时呈现的组件,例如:

<Route path={`${match.path}/:name`}
  render= {({match}) =>( <div> <h3> {match.params.name} </h3></div>)}/>

我只是想知道在这个例子中,({match}) 对象是从哪里来的,当它作为参数传递给 render prop 函数时......

【问题讨论】:

  • 你应该看看render props
  • 嗯我不明白那部分:&lt;Mouse render={mouse =&gt; ( &lt;Cat mouse={mouse} /&gt; )}/&gt; 传递给函数的这个{mouse =&gt; 参数是什么?它是event 对象的占位符吗?当onMouseMove 事件被触发时被触发?我在鼠标组件中没有看到与{this.props.render(this.state)} 的连接
  • 编辑:好的,我想我明白了,mouse 是从鼠标组件的 this.props.render 函数传递的 this.state 对象,它本身被传递给 cat 组件......跨度>

标签: javascript reactjs react-router react-props


【解决方案1】:

如果您不将 props 传递给子组件,它们将无法在子组件期间使用。看看渲染props

在反应路由器中Route 的情况下,Route 使用composition 将其道具传递给子道具。所以Route 的 props 将可用于直接子组件,但不能用于下一个子组件层次结构。

例子:

<Route props={props}>
   <Child1>
       will have props
       <Child2>
         will not have props if not passed from Child1
       </Child2>
   </Child1>
</Route>

【讨论】:

    猜你喜欢
    • 2018-06-20
    • 2020-06-03
    • 2020-08-06
    • 2019-01-27
    • 2019-09-08
    • 2021-10-05
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    相关资源
    最近更新 更多