Компонент React Native Text внутри компонента TextInput. Проблема в iOS: потеря фокуса при вводе текста внутри компонента TextInput

<Text
  style = {{
    justifyContent: "center",
    alignItems: "center",
    alignSelf: "center",
    textAlign: "left",
    textAlignVertical: "center",
    lineHeight: 40,
    width: screenWidth - 32,
  }}
>
  {textwithinput.map((item: any, index: number) => {
    return (
      <Text
        key = {index}
        style = {{
          color: themeColor.headertextColor,
          fontSize: getFontSize(16),
          // lineHeight: 40,
          fontFamily: fonts.openSansRegular4,
          justifyContent: "center",
          alignItems: "center",
          textAlign: "left",
          textAlignVertical: "center",
          alignSelf: "center",
        }}
      >
        {item.startsWith("TEXT_INPUT_") ? "" : item}
        {item.startsWith("TEXT_INPUT_") && (
          <TouchableOpacity
            style = {{
              padding: 0,
              // marginTop: Platform.OS == 'ios' ? 0 :10,
              backgroundColor: "red",
            }}
          >
            <TextInputPaper
              value = {inputValue}
              ref = {null}
              style = {{
                height: 26,
                width: 80,
                padding: 0,
                borderRadius: 5,
                paddingRight: 5,
                paddingLeft: 5,
                backgroundColor: colors.transparent,
                fontSize: getFontSize(16),
                fontFamily: fonts.openSansMedium5,
                color: themeColor.textColor,
                borderWidth: 1,
                borderColor: themeColor.selectedBG,
              }}
              keyboardType = "default"
              autoCorrect = {false}
              autoCapitalize = "none"
              // contentStyle = {{
              //   paddingLeft: 5,
              //   height: 26,
              //   paddingRight: 5,
              //   paddingTop: 0,
              //   paddingBottom: 0,
              // }}
              // mode = {'outlined'}
              onChangeText = {setInputValue}
            />
          </TouchableOpacity>
        )}
      </Text>
    );
  })}
</Text>

Я столкнулся с проблемой с компонентом TextInput в React Native, особенно на устройствах iOS. Всякий раз, когда я пытаюсь ввести текст внутри TextInput, я замечаю, что фокус теряется после ввода всего одного символа. Эта проблема отсутствует на устройствах Android, где TextInput ведет себя должным образом.

Я пытался исследовать потенциальные причины, такие как конфигурации клавиатуры, управление фокусом или свойства TextInput, но мне не удалось найти решение.

Кто-нибудь еще сталкивался с подобной проблемой? Если да, не могли бы вы предоставить идеи или возможные решения для решения этой проблемы? Любая помощь будет принята с благодарностью. Спасибо.

1
0
74
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Я попробовал другой способ решить эту проблему, проверьте код ниже.

    const paragraph='The heart functions as a pump at the centre of the circulatory system. In humans it TEXTINPUT_0 located in the chest cavity, between the lungs, a bit to the left. The heart consists of four chambers surrounded by a very strong muscular wall, the myocardium. The upper chambers, the right and left atria, TEXTINPUT_1 blood entering the heart, and the lower chambers, the right and left ventricles pump the blood out of the heart, via the pulmonary and the systemic circulatory systems. The two systems work as TEXTINPUT_2'
    
    // created component 
    const ParagraphWithInputs = ({ paragraph }) => {
      // Split the paragraph into words
      const words = paragraph.split(' ');
    
      // State to store input values
      const [inputValues, setInputValues] = useState({});
    
      // Function to handle text change in TextInput components
      const handleTextChange = (index, value) => {
        setInputValues({ ...inputValues, [index]: value });
      };
      console.info('sdhgfhdsfgud',inputValues);
      return (
        <View style = {{ flexDirection: 'row', flexWrap: 'wrap',width:screenWidth-32,alignSelf:'center' }}>
          {words.map((word, index) => {
            if (word.startsWith('TEXTINPUT_')) {
              // If the word is a TEXTINPUT placeholder, render a TextInput component
              const inputKey = word;
              return (
                <View key = {index} style = {{ flexDirection: 'row', alignItems: 'center' }}>
                  <TextInput
                    style = {{ borderWidth: 1, width: 100,height:26,borderRadius:5,marginEnd:5,padding:0 ,paddingHorizontal:3,}} // Fixed width for TextInput
                    value = {inputValues[word] || ''}
                    onChangeText = {(text) => handleTextChange(word, text)}
                  />
                </View>
              );
            } else {
              // If the word is regular text, render it within a Text component
              return <Text style = {{lineHeight:40}} key = {index}>{word} </Text>; // Add space after each word
            }
          })}
        </View>
      );
    };
// use component in your code
  <ParagraphWithInputs paragraph = {paragraph} />

Другие вопросы по теме