如何将React组件Button设为Section的默认children属性?
解决React组件默认children为另一个组件的问题
这个问题我之前也碰到过,核心原因是你搞混了React组件(函数/类)和React元素的区别:直接传Button相当于把组件函数本身作为children,而React需要的是渲染后的React元素(也就是<Button />对应的对象),所以才会抛出那个"Functions are not valid as a React child"的警告。
下面给你两种可行的解决方案:
方案一:在defaultProps中传入React元素
你可以通过React.createElement或者直接使用JSX语法,把Button转换成React元素后作为默认值:
import React from 'react'; import PropTypes from 'prop-types'; const Button = () => <button type="button">Test</button>; const Section = props => { const { children } = props; return ( <div>{children}</div> ); }; // 方式1:使用React.createElement(适合所有环境) Section.defaultProps = { children: React.createElement(Button) }; // 方式2:直接写JSX(需要项目支持Babel编译JSX,现在大部分React项目都支持) // Section.defaultProps = { // children: <Button /> // }; Section.propTypes = { children: PropTypes.node };
方案二:在组件内部通过解构赋值设置默认值
这种方式更灵活,尤其如果默认children需要依赖组件的其他props时更方便:
import React from 'react'; import PropTypes from 'prop-types'; const Button = () => <button type="button">Test</button>; const Section = props => { // 直接在解构时设置默认值,不存在children时就渲染<Button /> const { children = <Button /> } = props; return ( <div>{children}</div> ); }; Section.propTypes = { children: PropTypes.node };
为什么之前的写法无效?
当你写children: Button时,你传递的是组件的定义函数,而不是React可以渲染的元素。React在渲染children时,会检查每个子节点的类型:如果是函数,它会认为这是一个需要执行的渲染函数(比如render props),但这里你并没有执行它,所以就会抛出警告。而<Button />或者React.createElement(Button)会返回一个React元素对象,这才是React可以正常渲染的节点类型。
内容的提问来源于stack exchange,提问作者Chukwuemeka Inya
相关产品推荐
相关产品推荐

