我把一个表格控件和React放在一起,它基本上遵循这样的模式,一直到细胞:
class Table extends Component {
static propTypes = {
tableClass: PropTypes.string,
columnDefinitions: PropTypes.array.isRequired
}
constructor(props) {
super(props);
}
render() {
const { tableClass, children } = this.props;
const passthroughProps = except(this.props, ['id', 'key', 'children', 'form', 'tableClass']);
const transformedChildren = React.Children.map(children, c => React.cloneElement(c, passthroughProps));
return (
<div className={ `${ tableClass ? `${tableClass} ` : '' }table` }>
{ transformedChildren }
</div>
);
}
}
export default Table;except只是一个实用程序,它获取一个对象的所有“自有”属性(除了),用于第二个参数中定义的属性(作为属性名称的数组)。
在您告诉我使用高阶组件之前,让我提供一些更详细的内容。我之所以以这种方式设计表,是因为我希望人们能够像下面这样使用控件(在这里,他们可以提供自己的自定义实现)。
<Table columnDefinitions={columnDefinitions}>
<Row>
<Cell/>
<Cell/>
<Cell/>
</Row>
<CustomRow />
</Table>即使我想放弃类似于转换的方法,我也不太确定如何使用高阶组件来完成这个任务,因为它们似乎更适合于更确定的方法。为了澄清,我们有一个临时的Card和一个CardList
const CardListHOC = (Card) => CardList extends Component {
// propTypes, etc...
render() {
const { items } = this.props;
const passthroughProps = except(this.props, ['id', 'key', 'children', 'form', 'items']);
return (
{items.map(i => (<div className="card-list-wrapper"><Card {...passthroughProps} item={i}/></div>)}
);
}
}
const CardHOC = (Child) => Card extends Component {
// propTypes, etc...
render() {
const passthroughProps = except(this.props, ['id', 'key', 'children', 'form']);
return (
<div className="card-wrapper">
<Child {...passthroughProps} />
</div>
);
}
}CardListHOC只需要一种类型的Card,因此这意味着我传递给CardHOC的Child组件必须根据输入数据实现我想要支持的所有定制卡片类型的所有自定义逻辑。
React.cloneElement方法的问题是首先呈现子元素,因此在第一次传递时,子元素在被“转换”之前不会从它们的父元素获得道具--因此,您最终会出现很多效率低下的问题,例如,我不能让Row组件将columnDefinitions作为支撑,除非我将它们显式地传递给每个Row:
<Table columnDefinitions={columnDefinitions}>
<Row columnDefinitions={columnDefinitions}>
<Cell/>
<Cell/>
<Cell/>
</Row columnDefinitions={columnDefinitions}>
<CustomRow columnDefinitions={columnDefinitions}/>
</Table>有什么更好的方法来解决这个问题吗?也许有一种方法能让我不去看?如果有人能指出我的正确方向,这将是非常感谢!
发布于 2016-04-09 08:05:51
尽管它可能是令人惊讶的--我和昨天一样--但React元素并没有用React.createElement (又名<Element/>)实例化。您可以尝试,类只有在元素被挂载到DOM上时才会被实例化。这就是为什么cloneElement不是低效的,这也是为什么在转换子元素之前不会呈现它们的原因。
话虽如此,你可能会想看看反应上下文的一些魔法粉末。
https://stackoverflow.com/questions/36504787
复制相似问题