gpt4 book ai didi

javascript - 将一个 React 组件指定为另一个组件的 defaultProp

转载 作者:行者123 更新时间:2023-11-30 11:08:50 24 4
gpt4 key购买 nike

我有两个组件,SectionButton .我要Section接受ButtonString因为它是 child Prop 。如何指定 Button作为 Section 的默认 children Prop 。

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.

最佳答案

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

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

参见 working example

关于javascript - 将一个 React 组件指定为另一个组件的 defaultProp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54605690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com