如何在 React Native 中更改 TextInput 光标位置? [英] How to change TextInput cursor position in React Native?
问题描述
我正在尝试在 React Native 中实现这种行为:用户类型例如 5 然后.000"将自动添加到 TextInput
,但用户可以添加其他数字,例如7、最终结果应该看起来像57.000".
I am trying to achieve this behaviour in React Native: The user type for example 5 then ".000" will be added automatically to the TextInput
, but the user can add an other number for example 7, the final result should look like "57.000".
我试图找到一种解决方法,但计算了值的长度并相应地添加了字符,但没有按预期工作.
I tried to find a workaround but calculating the length of value and add chars accordingly but it didn't work as expected.
然后我找到了TextInput
的selection
道具.
这是我的看法:
我添加了这个状态
selection: {
start: 0,
end: 0
}
这是我的TextInput
<TextInput
onFocus={setSelection}
selection={selection}
keyboardType="numeric"
onChangeText={(text) => onChangeText("val", text)}
value={val}
editable={true}
selectTextOnFocus={false}
/>
这里是 onChangeText 方法
Here is onChangeText method
onChangeText = async (key, value) => {
var numDots = value;
if (value.indexOf(".000") === -1) {
numDots = value + ".000"
}
this.setState({ [key]: numDots });
};
这里是 setSelection 方法
And here is the setSelection method
setSelection = () => {
this.setState({ select: { start: 1, end: 1 } });
};
问题是每当我输入时,光标总是聚焦在索引 0
上,我认为 setSelection
没有被触发.
The problem is whenever I type, the cursor is always focusing on index 0
, I think setSelection
is not being triggered.
我做错了什么吗?
我希望有人能帮助我.提前谢谢.
I hope someone would help me in this. Thanx in advance.
推荐答案
You can do the following things to make it work
class YourComponent extends React.Component{
constructor(props) {
super(props);
this.state = {
text:'Hello World',
selection: {
start: 0,
end: 0
}
};
this.inputRefs = {};
}
setSelection = () => {
this.setState({ select: { start: 1, end: 1 } });
};
changeText = (val) => {
this.inputRefs.input.focus();
}
render(){
return(
<TextInput
onFocus={this.setSelection}
selection={this.state.setSelection}
onChangeText={val => {this.changeText(val)}}
value={this.state.text}
refName={ref => {
this.inputRefs.input = ref;
}}
/>
)
}
}
The idea is whenever your TextInput calls the onChangeText call-back put the focus on your TextInput through refs, as your component is responding to onFocus call back we will set the selection on that call back
这篇关于如何在 React Native 中更改 TextInput 光标位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!