Javascript 使用“ReactJS组件”;“子组件”;
我对ReactJS非常陌生,并开始制作如下组件:Javascript 使用“ReactJS组件”;“子组件”;,javascript,html,reactjs,Javascript,Html,Reactjs,我对ReactJS非常陌生,并开始制作如下组件: class Row extends React.Component { render() { return ( <div className={"row w-100 ml-0 mr-0 " + this.props.className}> {this.props.children} </div> );
class Row extends React.Component {
render() {
return (
<div className={"row w-100 ml-0 mr-0 " + this.props.className}>
{this.props.children}
</div>
);
}
}
类行扩展React.Component{
render(){
返回(
{this.props.children}
);
}
}
我现在想要实现的是,这个组件有“子组件”(我不知道它的正确名称)之类或类似的东西
我是否必须为此创建另一个组件,或者是否可以在一个组件中实现
编辑:
我有一个组件,里面已经有childs了:
<div className="custom-card">
<Card>
<CardHeader onClick={this.toggle} className={"card-header " + ((!this.props.readOnly && this.props.headerCtrl) && "pt-0")}>
<CardTitle className="card-title d-flex justify-content-between">
<p>{this.props.title}</p>
</CardTitle>
</CardHeader>
<Collapse isOpen={this.state.collapse}>
<CardBody className="card-body">
{this.props.children}
</CardBody>
</Collapse>
</Card>
</div>
{this.props.title}
{this.props.children}
但我也希望用户可以指定哪个组件应该显示在cardheader中。因此,不仅可以有
,还可以有
等等。您可以利用高阶组件(HOC)来提供自定义组件,同时保持其他零件不变。您的用例的典型HOC如下所示
const HeaderHOC = (Component) => {
return class extends React.Component {
render() {
<div className="custom-card">
<Card>
<CardHeader onClick={this.toggle} className={"card-header " + ((!this.props.readOnly && this.props.headerCtrl) && "pt-0")}>
<Component {...this.props} />
</CardHeader>
<Collapse isOpen={this.state.collapse}>
<CardBody className="card-body">
{this.props.children}
</CardBody>
</Collapse>
</Card>
</div>
}
}
}
const HeaderHOC=(组件)=>{
返回类扩展了React.Component{
render(){
{this.props.children}
}
}
}
当你想使用这个HOC时,你可以这样做
const CardTitleComp = (props) => (
<CardTitle className="card-title d-flex justify-content-between"><p>{props.title}</p></CardTitle>
)
const CustomComp = HeaderHOC(CardTitleComp);
constcardtitlecomp=(道具)=>(
{props.title}
)
const CustomComp=校长办公室(CardTitleComp);
如果我理解正确,您需要多个占位符,而不仅仅是一个子占位符
。幸运的是,由于React元素只是JavaScript对象,您可以将它们作为道具传递
当您有一个组件(
)具有与您问题中的渲染方法类似的渲染方法(未更改)时:
{this.props.title}
{this.props.children}
您可以传递标题的自定义组件,如下所示:
<CustomCard title={<SpecialTitle>My special title</SpecialTitle>}>
My card body!
</CustomCard>
我的牌身!
所以。。。你想达到什么目标?是否要将卡组件置于行中?或者什么?我编辑了这篇文章,也许现在更好理解了如果我正确理解了你,当用户单击某个东西时,你想隐藏和创建一些元素?但是我如何使用这个组件呢?我需要这样使用:@mantaplatte,是的,你可以按你说的写。代替CardTitle,如果你想使用CardBody,你可以简单地用CardBody创建自定义组件并传递所需的propsHm,我仍然不知道如何使用HeaderHOC。如果我想在页面上使用它,例如在这样的专栏中:这很简单,很好,谢谢!但是这种方式是一种好的“编码方式”吗?我相信是的。有不同的变体,一些直接传递元素,另一些传递返回元素的函数。React甚至有关于此模式的官方文档:
<CustomCard title={<SpecialTitle>My special title</SpecialTitle>}>
My card body!
</CustomCard>