【问题标题】:Adding subcomponent to component in React Native在 React Native 中向组件添加子组件
【发布时间】:2021-04-05 13:20:45
【问题描述】:

在我的代码中的某处,我使用 .map 函数创建一个组件数组,并使用这些组件更新状态。 ListItems 然后在 return() 函数中呈现。

我的问题是以后如何将子组件添加到组件中?就像在下面的代码中一样,“徽章”组件最初需要在那里,但后来添加以显示该用户有一条新的未读消息。如何做到这一点?

  var chatsWithUsersInfo = userInfo.map((message, index) => (
    <ListItem key={index} onPress={() => navigation.navigate('GiftedChat', { otherPersonUserId: message.userId }) }>
     <Avatar rounded source={{ uri: message.profilePictureURI }} />


     <Badge
     status="success"
     containerStyle={{ position: 'absolute', top: -4, right: -4 }}
     />

     <ListItem.Content>
       <ListItem.Title>{message.name}</ListItem.Title>
     </ListItem.Content>
   </ListItem>
  ))
  setChats(chatsWithUsersInfo)

以后如何向这个 ListItem 组件数组添加子组件?

【问题讨论】:

    标签: react-native components state


    【解决方案1】:

    React 有一些关于条件渲染的优秀文档https://reactjs.org/docs/conditional-rendering.html

    { message?.unread
      ? <Badge />
      : null
    }
    

    PS,通过将 React 组件列表放入 state 中,您将很难管理它。

    您的组件列表chatsWithUsersInfo 是从userInfo 派生的,因此请在渲染函数(或功能组件的函数体/返回)中计算它。让 React 处理反应性。

    const Chats = (props) => {
      return <Container>
        {userInfo.map(...)}
      <Container />;
    }
    

    参考:https://web.archive.org/web/20150419023006/http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-shouldnt-go-in-state

    编辑:更新您的问题。

    考虑这两个等效组件

    const Comp = ({}) => {
      const [count, setCount] = useState(0);
    
      // Markup is derived from state :+1:
      return <Button onPress={() => setCount(count + 1)}>
        {count && <Label>{count}</Label>}
      </Button>;
    };
    
    const Comp = ({}) => {
      const [count, setCount] = useState(0);
    
      // Let's set the Label component on state
      const [Label, setLabel] = useState(null);
    
      // Now we need to add a redundant render every
      // time count updates so we can update the Label
      // component and render again!
      useEffect(() => {
        if (count) setLabel(<Label>{count}<Label/>);
      }, [count]);
    
      return <Button onPress={() => setCount(count + 1)}>
        {Label}
      </Button>;
    };
    

    【讨论】:

    • 好的,如果没有其他方法可以使用徽章更新单个 ListItem 组件,那么我想条件渲染是可行的方法。您是否知道如何创建组件并将其道具链接到状态?就像我的另一个问题中的“半径”一样——现在它只在创建状态值时获取状态值,但在状态值更改时不会更新:stackoverflow.com/questions/65480668/…
    • 是的,不要将 React 组件置于状态。组件中的 return 语句应包含如何根据任何可能的状态/道具呈现 UI 的所有规则。不要将组件置于状态。
    • 感谢您回复我。然后将所需的变量置于状态,并在渲染/返回函数中运行一个 for 循环。 React 并不清楚为什么你应该保持状态的最低限度,但我想它在处理实际渲染/返回函数中的渲染时更有效..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    相关资源
    最近更新 更多