避免在重新渲染父对象时失去对TextInput的关注?

时间:2019-09-04 06:23:38

标签: javascript react-native

我的屏幕上有一个FlatList子级。该子级包含几个TextInputs和一些样式。我想在TextInputs的OnTextChange-功能中更新父状态。但是,在我当前的实现中,每当我在任何TextInputs中键入一个字符时,我都会失去焦点(键盘被关闭)。

如果我尝试在父屏幕中创建TextInput并更新每个onChangeText上的状态,则一切正常。

这是我的代码(删除了一些不重要的视觉组件):

UserInfoScreen.js

const onChangeText = (setUserInfo, userInfo) => (backendLabel, text) => {
  console.log(backendLabel, text);
  setUserInfo({ ...userInfo, [backendLabel]: text });
};

const UserInfoScreen = () => {
  const { state } = useContext(AuthContext);
  const [isEditing, setIsEditing] = useState(false);
  const [userInfo, setUserInfo] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phoneNr: '',
  });

...

  return (
    <View style={styles.root}>
      <SeparatedList
        onChangeText={onChangeText(setUserInfo, userInfo)}
        editable={isEditing}
        style={styles.list}
        content={[
          {
            label: 'FirstName:',
            text: userInfo.firstName,
            backendLabel: 'firstName',
          },
          {
            label: 'LastName:',
            text: userInfo.lastName,
            backendLabel: 'lastName',
          },
          { label: 'Email:', text: userInfo.email, backendLabel: 'email' },
          { label: 'Mobile:', text: userInfo.phoneNr, backendLabel: 'phoneNr' },
        ]}
      />
    </View>
  );
};

SeparatedList.js

const SeparatedList = ({ content, style, editable = false, onChangeText }) => {
  return (
    <View style={{ ...style }}>
      <FlatList
        bounces={false}
        data={content}
        renderItem={({ item }) => {
          return (
            <View style={styles.textContainer}>
              <CustomText style={styles.label}>{item.label}</CustomText>
              <TextInput
                editable={editable}
                onChangeText={text => onChangeText(item.backendLabel, text)}
              >
                <CustomText style={styles.text}> {item.text}</CustomText>
              </TextInput>
            </View>
          );
        }}
        ItemSeparatorComponent={() => <ListSeparator />}
        contentContainerStyle={styles.container}
        keyExtractor={it => `${it.label} ${Math.floor(Math.random() * 1000)}`}
      />
    </View>
  );
};

1 个答案:

答案 0 :(得分:0)

我修复了它。在排

keyExtractor={it => `${it.label} ${Math.floor(Math.random() * 1000)}`}

当我改用它时,它起作用了

keyExtractor={(item, index) => index.toString()}