Reactjs 在React中使用composition将组件拆分为base和child
我有以下组件,它是ag网格的包装器:Reactjs 在React中使用composition将组件拆分为base和child,reactjs,Reactjs,我有以下组件,它是ag网格的包装器: <div className="ag-theme-material" style={{height: "100%"}}> <AgGridReact pagination paginationPageSize={this.props.Size} columnDefs={this.props.Col} rowData={this.props.Row} /> &
<div className="ag-theme-material" style={{height: "100%"}}>
<AgGridReact
pagination
paginationPageSize={this.props.Size}
columnDefs={this.props.Col}
rowData={this.props.Row}
/>
</div>
我想创建一个单独的包装器,但没有分页功能。因此,我需要一个基类,该基类具有两个子类(带分页和不带分页)可以从中继承的公共特性。我知道React中很少使用继承,所以我想知道如何使用组合实现相同的效果。谢谢 您可以使用复合组件模式,在该模式中为组件提供基本功能,用户可以根据自己的喜好使用更多功能 代码如下所示:
import React, { Component } from 'react'
import ReactDom from 'react-dom'
class AgGridReact extends Component {
static Paginator = (props list) => (...) // some jsx that represents the paginator
render() {
return <>
/** your grid jsx code here **/
// other features code
React.Children.map(this.props.children, child =>
React.cloneElement(child, {
// props you need to pass for the components
}),
)
}
</>
}
// the usage of this component will be:
<AgGridReact {...props}>
// the user can git rid of this if without paginator
<AgGridReact.Paginator />
</AgGridReact>
import React,{Component}来自“React”
从“react dom”导入react dom
类AgGridReact扩展组件{
静态分页器=(道具列表)=>(…)//表示分页器的某些jsx
render(){
返回
/**您的网格jsx代码在这里**/
//其他功能代码
React.Children.map(this.props.Children,child=>
反应。克隆元素(儿童{
//组件需要传递的道具
}),
)
}
}
//此组件的用途如下:
//如果没有paginator,用户可以git摆脱此问题
您可以使用复合组件模式,为组件提供基本功能,用户可以根据自己的喜好使用更多功能
代码如下所示:
import React, { Component } from 'react'
import ReactDom from 'react-dom'
class AgGridReact extends Component {
static Paginator = (props list) => (...) // some jsx that represents the paginator
render() {
return <>
/** your grid jsx code here **/
// other features code
React.Children.map(this.props.children, child =>
React.cloneElement(child, {
// props you need to pass for the components
}),
)
}
</>
}
// the usage of this component will be:
<AgGridReact {...props}>
// the user can git rid of this if without paginator
<AgGridReact.Paginator />
</AgGridReact>
import React,{Component}来自“React”
从“react dom”导入react dom
类AgGridReact扩展组件{
静态分页器=(道具列表)=>(…)//表示分页器的某些jsx
render(){
返回
/**您的网格jsx代码在这里**/
//其他功能代码
React.Children.map(this.props.Children,child=>
反应。克隆元素(儿童{
//组件需要传递的道具
}),
)
}
}
//此组件的用途如下:
//如果没有paginator,用户可以git摆脱此问题
您可以使用高阶组件(HOC)进行此操作。常见功能有哪些?所以我们可以建议最好的方法是什么now@UtsavPatel你能举个例子吗?你可以使用高阶组件(HOC)来实现这一点。有什么共同的功能?所以我们可以建议最好的方法是什么now@UtsavPatel你能举个例子吗?我不知道我是否理解//组件需要传递的道具
这意味着要包括子组件或父组件的道具吗?在这种情况下,需要传递给Paginator(子组件)的道具不确定我是否理解//组件需要传递的道具
是指包含子级还是父级的道具?在这种情况下,需要传递给Paginator(子级)的道具