问题
React Native的TextInput在iOS平台当你设置了value
和defaultValue
等prop的时候,会发现输入中文,不管用了,会将拼音自动转换为英文字母显示!(Android平台没有这个问题)
在Github上搜索了一下,发现有大量的issue都在说这个事情,不仅中文,在输入韩文,日文的时候会同样存在这个问题!
原因
在这个issue中,@Swordsman-Inaction的回答中:
- Enter some random word
- Click outside of the TextInput
- The textFieldDidChange gets called twice immediately, _nativeEventCount is increased by 2.
- The _onChange gets called immediately.
- this._inputRef.setNativeProps in _onChange is supposed to set native prop _mostRecentEventCount before the text is rendered, but somehow it didn’t.
- So the eventLag is larger than 0, and the correct text could not be set.(Even thought the native UITextField’s text shouldn’t be wrong I think).
- Shit happens…
还有就是:textFieldDidChange
,onChangeText
等回调方法,在输入中文的时候都会回调两次!!!!
解决方案
非正式方案
有一个方案:
export default 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} />;
}
}
这个方案能解决设置value
等之后不能输入中文的问题,但是可能带来别的问题!
所以,此方案慎用!
官方方案
喜大普奔,在release了这么多版本之后,终于在0.57中修复了这个问题!
在0.57的changelog中,第4条:
Fix controlled
<TextInput>
on iOS when inputting in Chinese/Japanese (892212b by @mmmulani)
所以,最好还是把版本升级一哈!