В React-Native расположение курсора не меняется, когда я обновляю TextInput с помощью кнопки - PullRequest
0 голосов
/ 20 июня 2020

У меня есть многострочный TextInput и ряд кнопок. Нажимая эти кнопки, я пытаюсь обновить TextInput. Например, если пользователь вводит «15», а затем, нажав кнопку, он может добавить «00» после 15, теперь ввод будет «1500», здесь поведение курсора правильное, поскольку текст добавляется в конец значения TextInput. Но когда пользователь пытается добавить «00» с помощью кнопки между значениями текстового ввода, тогда местоположение курсора не обновляется, например, если пользователь вводит с клавиатуры 75 и хочет поместить «00» между 7 и 5, тогда курсор будет похож на «70». | 05 ".

Вот что я написал:

Из родительского компонента вызывается дочерний компонент, который содержит список кнопок

import React,{useState,createRef} from 'react'
import {View,Text,StyleSheet,TextInput,ScrollView,Clipboard } from 'react-native'
import {Icon,Input,Button} from 'react-native-elements'
import ChildComponent from '../components/ChildComponent'



const ParentComponent=()=>{
const [input,SetInput]=useState("")
const [CursorLocation,SetCursorLocation]=useState(input.length);


    const inputR = createRef();
    
    const updateString=(text,addedText)=>{
    SetInput(text)
    }
    
    const UpdateTextInput=(ip,callType)=>{
    if(callType=='TEXT'){
    updateString(input.slice(0,CursorLocation)+ip+input.slice(CursorLocation),ip)
    }
    }
    
    
    return (
    <View style={styles.viewStyle} keyboardShouldPersistTaps={'handle'}>
    
    <View style={{flex:3,backgroundColor:'#eee',margin:5,justifyContent:'flex-start',alignItems:'flex-start'}}>
    <TextInput
    ref={inputR}
    multiline
    textBreakStrategy='simple'
    autoCapitalize='none'
    underlineColorAndroid='transparent'
    style={{backgroundColor: '#eee',letterSpacing:2,width:'100%',textAlignVertical: 'top',fontSize:15,borderColor:'#bbb',color:'#009999',paddingHorizontal:5,borderRadius:5}}
    autoFocus={false}
    autoCompleteType='off'
    autoCorrect={false}
    value={input}
    selectionColor={'red'}
    numberOfLines={20}
    onSelectionChange={(event) =>{SetCursorLocation(event.nativeEvent.selection.end)}}
    onChangeText={(text)=>updateString(text,'')}
    />
    </View>
    
    
    <View style={{flexDirection:'row',backgroundColor:'#fff'}}>
    <CodeElement callBackFunc={(ip,callType)=>UpdateTextInput(ip,callType)}/>
    </View>
    
    </View>
    )
    }
    
    
    export default ParentComponent;

Дочерний компонент:

import React, { useRef, useEffect } from 'react'
import {TouchableOpacity,Text,View,ScrollView} from 'react-native'
import { Icon } from 'react-native-elements';

const ChildComponent=({callBackFunc})=>{

const DATA=[
{'text':'0','input':'0','key':'115661'},
{'text':'00','input':'00','key':'1155661'},
{'text':'000','input':'000','key':'1415661'},
{'text':'0000','input':'0000','key':'1156261'},
{'text':'00000','input':'00000','key':'1175661'}
];




const Item=()=>{
return (
DATA.map((item)=>{
return (
<TouchableOpacity
key={item.key} 
onPress={()=>callBackFunc(item.text,'TEXT')}
style={{paddingHorizontal:25,paddingVertical:6,borderColor:'tomato',borderEndWidth:.4}}
>
<Text style={{fontSize:20,fontWeight:'bold',color:'#666'}}>{item.text}</Text>
</TouchableOpacity>
)
})

)
}
return (

<View style={{flexDirection:'row-reverse'}}>

<ScrollView horizontal={true} 
showsHorizontalScrollIndicator={true}
keyboardShouldPersistTaps={'handle'}
invertStickyHeaders={false}
style={{flexDirection:'row',marginRight:60}}
>
    <Item/>
</ScrollView>
<TouchableOpacity activeOpacity={.4}
onPress={()=>callBackFunc('','RUN')}
 style={{position:'absolute',flexDirection:'row',backgroundColor:'tomato'}}>
<Text style={{textAlign:'center',paddingVertical:10,paddingLeft:5,marginRight:-10,color:'#eee',fontWeight:'bold'}}>SAVE</Text>
<Icon
name='play-arrow'
size={25}
type='material'
iconStyle={{color:'#eee',textAlign:'center',paddingVertical:7,paddingStart:5}}

/>

</TouchableOpacity>

</View>
)

}

export default ChildComponent

Я что-то делаю не так?

Надеюсь, кто-нибудь мне в этом поможет. Заранее спасибо

Adding zeros at the end of textinput, which working as expected

Добавление нулей в середине TextInput, положение курсора не изменяется должным образом

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...