我有两个组成部分,Section
和Button
。我希望Section
接受Button
或String
作为儿童道具。如何将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.
答案 0 :(得分:2)
答案 1 :(得分:1)
将其他组件指定为默认道具是不明智的做法,因为您正在打破松散的耦合,并且您的Button应该具有自己的道具,例如text
和onClick
才能起作用。但是如果您愿意,可以进行条件渲染。
const Section = props => {
const { children } = props
const content = children ? children : <Button />
return (
<div>{content}</div>
)
}