Override/Disable iOS Smart Punctuation in TextInput

≡放荡痞女 提交于 2020-03-19 19:42:27

问题


React Native 0.59.9 with device running iOS 11, and Smart Punctuation enabled. This iOS feature automatically converts entered text into more visually-pleasing notations.

Examples:

  • double hyphen -- gets autoconverted to an emdash (unicode 8212)
  • quotation mark " gets autoconverted to a curly quote (unicode 8220)

etc.

Disabling Smart Punctuation (via Settings > General > Keyboard) is unfortunately not an option.

I render a basic TextInput component almost exactly as per the RN docs, with the only exception that I'm using my own onChangeText handler function to see the effect on the entered text:

import React, { Component } from 'react';
import { TextInput } from 'react-native';


function handleTextChange(value) {
  // check value here after entering a '-' in the rendered TextInput.
  // when initial value is set to '', received value is ascii 45
  // when initial value is set to '-', received value is unicode 8212
}

export default function UselessTextInput() {
  const [value, onChangeText] = React.useState('-'); // change this to '' to see the difference

  return (
    <TextInput
      style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
      onChangeText={(text) => handleTextChange(text)}
      value={value}
    />
  );
}

Setting autoCorrect={false} and/or autoCompleteType='off' on the <TextInput> have no effect on the entered text.

Question
Is there a way to override this auto-correct behaviour so as to not change the user's inputted data?

I see that someone asked Facebook RN this question via a Github issue, but got no response.


回答1:


Indeed, this is an issue with the TextInput's iOS implementation, but I can provide a workaround for you. The trick is to check the TextInput's value for special characters and then replace those characters appropriately. See example below, where I replace every "—" with "--".

Code

const UselessTextInput = () => {
  const [value, setText] = React.useState('-'); // change this to '' to see the difference

  function handleTextChange (value) {
    var val = value;
    // check if value contains special characters 
    if (value.includes("—")){
      //replace values appropriately
      val = value.replace("—", "--");
    }
    //set new text 
    setText(val);
  }
  return (
    <TextInput
      style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
      onChangeText={(text) => handleTextChange(text)}
      value={value}
    />
  );
}

Working Example:

https://snack.expo.io/rJkj95ePB



来源:https://stackoverflow.com/questions/57983965/override-disable-ios-smart-punctuation-in-textinput

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!