在每次击键反应本机后,TextInput失去焦点

时间:2019-12-30 21:48:38

标签: react-native

我有以下代码(完整示例):

import React, { useState, useEffect } from 'react';
import { SafeAreaView, View, TextInput, Button, StyleSheet } from 'react-native';

const App = () => {
  const [textblocks, setTextblocks] = useState([]);
  const CreateTextBlockHandler = () => {
    let array = [...textblocks];
    array.push({text: ''});
    setTextblocks(array);
  };
  const SaveTextHandler = (index, text) => {
    let array = [...textblocks];
    array[index].text = text;
    setTextblocks(array);
  };
  const RenderTextInputs = () => {
      return textblocks.map((item, index) => {
        return (
          <View key={index}>
            <TextInput style={styles.textinput} placeholder="text" value={textblocks[index].text} onChangeText={value => SaveTextHandler(index, value)} />
          </View>
        );
      });
  };
  return (
    <SafeAreaView style={styles.pancontainer}>
      <RenderTextInputs />
      <Button title="Create textblock" onPress={CreateTextBlockHandler} />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  pancontainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  textinput: {
    width: 200,
    margin: 10,
    borderWidth: 1,
    borderColor: 'black'
  }
});

export default App;

工作原理:我有一个按钮可以动态添加新的textinput。这可行。问题是,对于我在文本输入中输入的每个字符,焦点在每个字符之后都会丢失。

我制作了小吃,您可以在这里进行测试:https://snack.expo.io/BJcHxluyI

认为,我需要将对textinput的引用保存在某个地方,然后在每次按键后将焦点移回textinput上,但是我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

更改

return (
    <SafeAreaView style={styles.pancontainer}>
      <RenderTextInputs />
      <Button title="Create textblock" onPress={CreateTextBlockHandler} />
    </SafeAreaView>
  );

收件人

return (
    <SafeAreaView style={styles.pancontainer}>
      {RenderTextInputs()}
      <Button title="Create textblock" onPress={CreateTextBlockHandler} />
    </SafeAreaView>
  );

或将RenderTextInputs放在App外面,并通过道具传递数据。使用第一种语法,react将RenderTextInputs视为一个组件,并嵌套在App中,将其再次安装在每个App渲染上。