How to customize nested components?

2019-09-11 21:30发布

How to customize nested components?

I'm building React Native app with Redux. I have three screens in my app that render list of users.

Follower/Following should show FollowButton:

<FollowersContainer> 
  <UserList onFollow={func} onUnfollow={func} users={[...]}>
    <UserCard user={user} onFollow={func} onUnfollow={func}>
      <FollowButton onFollow={func} onUnfollow={func} isFollowing={bool} userId={string} />
    </UserCard>
  </UserList>
</FollowersContainer>

Ask question screen should show AskButton:

<AskQuestionContainer> 
  <UserList onAsk={func} users={[...]}>
    <UserCard user={user} onAsk={func}>
      <AskButton onPress={onAsk} />
    </UserCard>
  </UserList>
</AskQuestionContainer>

Search Results should not show any button

<SearchResultsContainer> 
  <UserList users={[...]}>
    <UserCard user={user} />
  </UserList>
</SearchResultsContainer>

As you can see, all three screens uses UserList and UserCard components.

Currently UserList and UserCard needs to know about onFollow onUnfollow and onAsk actions and how to pass them around.

This can get complicated and not very flexible.

Ideally I want to do something like:

<UserList 
  rowComponent={
    <UserCard button={<FollowButton />} />
  }
/>

But how do I pass the actions from the top level component into the actual button? and How do I know which actions to pass?

I could use connect on the actual buttons to pass them the actions directly but I prefer these components stay pure and flexible.

Any suggestion on how to solve it in a clean way?

Thanks, Ran.

1条回答
对你真心纯属浪费
2楼-- · 2019-09-11 22:04

You can pass components as a prop.

render() {
  var passedButton = (<FollowButtton />);
  var row = (<UserCard button={passedButton} />);
  return (
    <UserList rowComponent={row}/>
  );
};

查看更多
登录 后发表回答