从React Native功能组件和useState中的数组映射函数动态渲染内容

时间:2020-11-02 15:30:23

标签: typescript react-native

我有一个功能组件,可以使用一些输入元素来呈现简单的表单。

我希望能够在用户单击按钮时动态添加输入元素。 我正在使用useState钩子,并创建了onChange箭头函数,如下所示:

  const [players, setPlayers] = useState<PlayerModel[]>([
    { id: 0, firstName: "", lastName: "" },
  ]);

  const handleOnAddPlayerPress = () => {
    let newPlayers = players;
    newPlayers.push({ id: newPlayers[newPlayers.length - 1].id + 1, firstName: "", lastName: "" });
    setPlayers(newPlayers);
  } 

我正在使用数组映射功能渲染玩家,如下所示:

{players.map((player, index) => {
      return <Input key={index} label={`Player #${player.id}`} />;
    })}

当用户单击按钮时,我将调用onChange函数,如下所示:

<Button
  onPress={handleOnAddPlayerPress}
  type="clear"
  icon={
    <Icon
      raised={true}
      name="user-plus"
      underlayColor="black"
      type="font-awesome"
      reverse
    />
  }
></Button>

一起:

import React, { useState } from "react";
import { ScrollView } from 'react-native';
import { Overlay, Input, Button, Icon } from "react-native-elements";
import { PlayerModel } from "../../models/PlayerModel";

export namespace AddNewTournamentForm {
  export interface Props {
    isVisible: boolean;
    onBackdropPress: () => void;
  }
}

export const AddNewTournamentForm = (
  props: AddNewTournamentForm.Props
): JSX.Element => {
  const [players, setPlayers] = useState<PlayerModel[]>([
    { id: 0, firstName: "", lastName: "" },
  ]);

  const handleOnAddPlayerPress = () => {
    let newPlayers = players;
    newPlayers.push({ id: newPlayers[newPlayers.length - 1].id + 1, firstName: "", lastName: "" });
    setPlayers(newPlayers);
  } 



  return (
    <Overlay {...props} fullScreen>
      <ScrollView>
        ...
        {players.map((player, index) => {
          return <Input key={index} label={`Player #${player.id}`} />;
        })}
        <Button
          onPress={handleOnAddPlayerPress}
          type="clear"
          icon={
            <Icon
              raised={true}
              name="user-plus"
              underlayColor="black"
              type="font-awesome"
              reverse
            />
          }
        ></Button>
        ...
      </ScrollView>
    </Overlay>
  );
};

但是,当发生更改时,布局似乎并没有重新呈现自身。 另一个奇怪的事情是,当我离开该叠加层并返回时,只有这样,我才能根据玩家人数看到输入元素的更新数量(这很奇怪,因为如果我进入并进入“叠加层”,状态应为启动)。

有什么建议吗? :)

1 个答案:

答案 0 :(得分:0)

尝试这种方式

const handleOnAddPlayerPress = () => {
    const newPlayers = [...players]; <-- Do this -->
    newPlayers.push({ id: newPlayers[newPlayers.length - 1].id + 1, firstName: "", lastName: "" });
    setPlayers(newPlayers);
}