代码之家  ›  专栏  ›  技术社区  ›  Chukwuemeka Inya

指定一个反应组件作为另一个组件的默认属性

  •  1
  • Chukwuemeka Inya  · 技术社区  · 7 年前

    我有两个组件, Section Button . 我想要 截面 接受 纽扣 或A String 因为它是儿童道具。我如何指定 纽扣 作为节的默认子属性。

    const Button = () =>
        <button type="button">Test</button>
    
    const Section = props => {
      const { children } = props
        return (
          <div>{children}</div>
        )
    }
    
    Section.defaultProps = {
        children: /* ??? */
    }
    
    Section.propTypes = {
        children: PropTypes.node
    }
    

    我尝试了以下方法:

    Section.defaultProps = {
        children: 'Section Test'     //Works fine
    }
    

    但是:

    Section.defaultProps = {
        children: Button /* does not work */
    }
    

    我得到以下错误:

    Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

    2 回复  |  直到 7 年前
        1
  •  2
  •   Ana Liza Pandac    7 年前

    正如错误消息暗示的那样,而不是使用 Button 使用 <Button /> .

    Section.defaultProps = {
      children: <Button />
    }
    

    working example

        2
  •  1
  •   dporechny    7 年前

    将其他组件指定为默认的属性是一个糟糕的实践,因为您打破了松散耦合,并且您的按钮应该有它自己的属性,比如 text onClick 发挥作用。但是如果你想这样做,你可以做条件渲染。

    const Section = props => {
      const { children } = props
      const content = children ? children : <Button />
      return (
        <div>{content}</div>
      )
    }