如何在Textinput中设置自定义光标位置?

时间:2019-07-01 15:05:01

标签: javascript react-native position cursor textinput

我正在尝试设置光标的响应位置。
我将TextInputMask用于货币等掩码值。

我正在尝试做类似的事情

案例:

  1. 开始
  

我在TextInput中的默认值=> 0,00

  1. 用户首次单击TextInput输入类型
  

我希望我的光标位置== 0 |,00

  1. 之后,当用户键入数字时,光标位置必须与之前相同
  

类似于=> 123 |,00

的值
  1. 如果用户按下逗号按钮(',')
  

光标必须类似于=> 123,0 | 0或123,| 00

的状态
  1. 当用户键入数字时,必须像在键盘上的插入文字一样写

    例如:
  

用户按2 => 123 |,12之后,用户按1 => 123,1 | 0(插入   
并像案例开始一样继续

我当前的应用Gif:

  

它可以在某些情况下执行,但是当我按逗号时我不能写插入内容。

Click for gif

我当前的一些代码:

this.state = {
        selection: {start: 0, end: 0},
        noCents: true,
        firstFocus: true,
        count: 0
    };

。     。     

setSelection = () => {
    if (this.state.firstFocus) {
        this.setState({selection: {start: 1, end: 1}});
        this.setState({firstFocus: false})
    }
};

。     。     

doJob(amount) {
    if (this.state.count === 2 && !this.state.noCents) {
        this.setState({
            count: 0,
            noCent: true
        })
    }
    if (amount.length !== 0 && this.state.noCents) {
        this.setState({
            selection: {
                start: amount.length - 3,
                end: amount.length - 3
            }
        });
    } else if (amount.length !== 0 && !this.state.noCents) {
        this.setState({count: this.state.count + 1});
        if (this.state.count === 1) {
            this.setState({
                selection: {
                    start: amount.length - 2,
                    end: amount.length - 2
                },
            });
        }
        if (this.state.count === 2) {
            this.setState({
                selection: {
                    start: amount.length - 1,
                    end: amount.length - 1
                },
            });
        }}
}

。     。     

<TextInputMask
  style={styles.input}
  type={'money'}
  options={{
    precision: 2,
    separator: ',',
    delimiter: '.',
    unit: '',
    suffixUnit: '',
    zeroCents: this.state.noCents
  }}
  value={this.props.amount}
  onChangeText={amount => this.props.amountChanged({
        props: 'amount',
        value: amount
    },
    this.doJob(amount))}
  onFocus={this.setSelection}
  selection={this.state.selection}
  //for press comma
  onKeyPress={(e) => (e.nativeEvent.key === ',' ? this.setState({noCents: false}) : null)}/>

0 个答案:

没有答案
相关问题