React-将组件作为参数传递给另一个组件

时间:2020-05-08 07:40:46

标签: reactjs react-native

我想拥有可以根据调用的屏幕来自定义视图的标题。所以我需要将组件作为参数传递给标头组件。但这似乎不起作用。

这是我的自定义组件

...    
const ComponentRight = () => {
      return (
        <Right>
            <Button transparent onPress= {() => {
                {enablePinned ?
                  addChatPinned(chatSelected) :
                  removeChatPinned(chatSelected)
                }
            }}>
              {enablePinned ?
                <Icon type= 'MaterialCommunityIcons' name= 'pin'/> :
                <Icon type= 'MaterialCommunityIcons' name= 'pin-off'/>
              }
            </Button>
            <Button 
              transparent
              onPress= {() => deleteChatList(chatSelected)}>
              <Icon type= 'FontAwesome5' name= 'trash' style= {{fontSize: 20}}/>
            </Button>
            <Button transparent>
              <Icon type= 'MaterialIcons' name= 'archive' style= {{fontSize: 25}}/>
            </Button>
          </Right>
      )
    }

    return (
      <Container>
        {showAction ?
          <SelectHeader
            onBack= {resetChatSelected()}
            itemCount= {chatSelected.length}
            componentRight= {ComponentRight}/> // passing my component as argument
...

这是我的标头组件

const SelectHeader = ({onBack, itemCount, componentRight}) => {
    return (
        <Header style= {appStyles.headerBackgroundColor}>
            <Left style= {{flexDirection: 'row'}}>
              <Button 
                transparent 
                style= {{marginRight: 30}}
                onPress= {() => {onBack}}>
                <Icon type='Ionicons' name= 'md-arrow-back' style= {{fontSize: 25}} color= 'white'/>
              </Button>
              <Title style= {appStyles.appTitle, {alignSelf: 'center'}}>{itemCount}</Title>
            </Left>
            <Body/>
            {componentRight}
          </Header> 
    )
}

export default SelectHeader

有人知道如何做到这一点吗?谢谢

2 个答案:

答案 0 :(得分:0)

您可以传递这样的组件:

<MyComponent
  propComponent={<MyPropComponent />}
/>

如有必要,您甚至可以将道具传递给该组件。

答案 1 :(得分:0)

这称为高阶组件[1],只需将组件作为道具传递并在render方法中使用它即可。

  1. https://reactjs.org/docs/higher-order-components.html
相关问题