指定一个React组件作为另一个组件的defaultProp

时间:2019-02-09 11:17:21

标签: javascript reactjs

我有两个组成部分,SectionButton。我希望Section接受ButtonString作为儿童道具。如何将Button指定为Section的默认子道具。

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 个答案:

答案 0 :(得分:2)

如错误消息所暗示,请使用Button而不是<Button />

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

请参见working example

答案 1 :(得分:1)

将其他组件指定为默认道具是不明智的做法,因为您正在打破松散的耦合,并且您的Button应该具有自己的道具,例如textonClick才能起作用。但是如果您愿意,可以进行条件渲染。

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