3 回答
TA贡献2036条经验 获得超8个赞
我想你想要的是所谓的 JSX 命名空间?无论哪种方式,您都可以实例化 Sample,然后添加更多组件作为 Sample 的属性(将其视为一个对象):
import React from "react"
const Sample = ({ children }) => (
<div className="panel">
{children}
</div>
)
Sample.Title = (props) => <div className="title">{props.children}</div>
Sample.Body = (props) => <div className="body">{props.children}</div>
export default Sample
注意:React 使用className而不是class因为我们使用的是 JSX。
TA贡献1789条经验 获得超8个赞
该Childrenutils的套装可以为您的情况有帮助。
import { Children } from 'react'
const Sample = ({ title, children }) => {
let _body, _title
Children.forEach(children, child => {
if (child.type === SampleTitle) {
return _title = child
}
if (child.type === SampleBody) {
return _body = child
}
})
if (!_title) _title = <div className='title'>{title}</div>
if (!_body) _body = <div className='title'>{children}</div>
return (
<div className='panel'>
{_title}
{_body}
</div>
)
}
const SampleTitle = ({ children }) => <div className='title'>{children}</div>
const SampleBody = ({ children }) => <div className='body'>{children}</div>
Sampe.Title = SampleTitle
Sample.Body = SampleBody
现在您可以通过多种方式使用 Sample:
<Sample title="my title">
<div>my body</div>
</Sample>
<Sample title="my title">
<Sample.Body>my body</Sample.Body>
</Sample>
<Sample title="my fallback title">
<Sample.Title>my overriding title</Sample.Title>
<Sample.Body>my body</Sample.Body>
</Sample>
TA贡献1993条经验 获得超5个赞
在这种情况下,您只需要将相关容器提取到它们自己的组件中:
const Sample = ({children }) => (
<div className="panel">{children}</div>
);
const Title = ({children}) => (
<div className="title">{children}</div>
);
const Body = ({children}) => (
<div className="body">{children}</div>
);
Sample.Title = Title;
Sample.Body = Body;
另请注意,css 类的正确道具是className.
添加回答
举报