【问题标题】:Automatic this.props.children in nested components嵌套组件中的自动 this.props.children
【发布时间】:2016-04-22 04:13:55
【问题描述】:

我正在通过react-router-tutoriallesson 5 并有一个问题。

本课讲定义一个NavLink组件,包装Link组件,并赋予它一个activeClassName属性,使用如下:

<NavLink to="/about">About</NavLink>

在课程中,他们将NavLink 组件定义如下:

// modules/NavLink.js
import React from 'react'
import { Link } from 'react-router'

export default React.createClass({
  render() {
    return <Link {...this.props} activeClassName="active"/>
  }
})

让我感到困惑的是自闭Link 组件的使用。在NavLink 的定义中没有提到将this.props.children 放在Link 组件内。我明确地尝试如下:

export default class extends React.Component {
    render() {
        return (
            <Link {...this.props} activeClassName="active">{this.props.children}</Link>
        )
    }
}

这也可以按预期工作。我的问题是为什么?是什么允许在其定义中的自闭合Link 组件自动获取NavLinkthis.props.children 并将其放入Link 组件中?

【问题讨论】:

    标签: reactjs jsx


    【解决方案1】:

    这是由于 Link 组件 {...this.props} 上的 spread 属性。这允许将包含this.props.childrenthis.props 的所有属性传递到链接组件中。 Here 是它的参考。

    【讨论】:

    • 太棒了,谢谢!我已经看过关于 this.props 使用扩展运算符的文档,但认为它只为标签做属性,而不是标签的内容。搞定了!
    猜你喜欢
    • 2017-12-31
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2017-08-10
    • 2022-11-22
    • 2018-11-22
    • 2019-01-19
    相关资源
    最近更新 更多