如何在React中克隆孩子

问题描述 投票:0回答:1

我想写一个简单的组件,它确实克隆了它的子组件并添加了一个marginBottom: 30

使用<View>作为兄弟,这确实很有用。不幸的是,它不能使用组件作为兄弟。

CustomListItem组件:

// @flow
import * as React from 'react';

type Props = {
  children: React.Node,
};

/**
 *
 */
function CustomListItem ({ children }: Props) {
  return React.Children.map(children, child => {
    const style = [
      child.props.style,
      { marginBottom: 30 },
    ];
    return React.cloneElement(child, { style });
  });
}

export default CustomListItem;

使用该组件的结果:

// works
<CustomListItem>
    <Text>This is great.</Text>
</CustomListItem>

// works as well
<CustomListItem>
    <View>
        <CustomComponent></CustomComponent>
    </View>
</CustomListItem>

// does not work. Why?
<CustomListItem>
    <CustomComponent></CustomComponent>
</CustomListItem>

这是我用于测试目的的CustomComponent:

// @flow
import * as React from 'react';
import { View } from 'react-native';

type Props = {
  children: React.Node,
};

function CustomComponent(props: Props) {
  return <View>{props.children}</View>;
}

export default CustomComponent;

如果我插入<Text><View>元素作为我的<CustomComponent>的孩子并不重要,所以我没有在这个例子中插入它。

javascript react-native
1个回答
2
投票

那是因为你的组件没有委托样式道具。在React中,将style传递给自定义组件不会自动设置样式,您必须手动设置它:

type Props = {
  children: React.Node,
  style: object
};

function CustomComponent(props: Props) {
  return <View style={props.style}>{props.children}</View>;
}

这将从style捕获props属性并将其应用于包装View


您可以使用更高阶的组件,但它会变得几乎相同,但您可以使其更具可重用性:

const withStyles = (component, style) => React.cloneElement(component, { style });

然后用它作为:

return withStyles(child, style);

通常HOC会引用实际的组件函数或类,如CustomComponent,而不是已创建的元素。但在这种情况下,你不是这样,他们没有那么有用。

© www.soinside.com 2019 - 2024. All rights reserved.