巧妙修复React-Native TextInput无法输入中文

接手的项目为React-Native0.55.4版本,发现TextInput 在iOS平台上无法输入中文的问题。
查询资料后发现该问题是react-native在0.54的版本以后,TextInput组件出现bug导致不能使用它的 value 或 defaultValue 属性。

下面是重点!!!
下面是重点!!!
下面是重点!!!

解决方案如下:

方案一:
用新组件MyTextInput替换TextInput

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

class MyTextInput extends Component {
    shouldComponentUpdate(nextProps){

        return Platform.OS !== 'ios' || (this.props.value === nextProps.value &&
            (nextProps.defaultValue == undefined || nextProps.defaultValue == '' )) ||
            (this.props.defaultValue === nextProps.defaultValue &&  (nextProps.value == undefined || nextProps.value == '' ));

    }

    render() {
        return <TextInput {...this.props} />;
    }
};

 export default MyTextInput;

自行封装MyTextInput组件,全局使用即可。

方案二:
设置全局变量,代替setState方法,此处this.carNumTxt为全局变量

<TextInput
    style={styles.inputItem}
    value={this.state.carNum}
    underlineColorAndroid='transparent'
    maxLength={9}
    onChangeText={(value) => {
        if(!(deviceInfo.deviceOS === 'ios')){
            this.setState({
                carNum: value
            })
         }

         this.carNumTxt = value
     }}
     placeholder="请输入车辆号"
/>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容