文章目录
问题描述
在升级至 React Native 0.62.2
过程中出现了许多问题,其中一个有趣的问题就是,在 iOS
平台中 TextInput
如果输入以中文开头就会出现抖动,文字大小显示异常的情况,功能虽然正常,但是用户体验着实差。
进过一番搜索,也有开发者出现了同样的问题,详细问题描述: 0.62 iOS TextInput font is shaking with chinese
解决方案
很快,在 Github 中就有了修复代码(非常感谢),查看详情。
虽然问题已找到,修正代码也有,但是要在下个版本中才能修复这个问题。如何才能在不升级的情况下解决?
首先看到修复代码更新了两个文件,添加代码不多,如下:
解决思路
首先想到的就是在安装完依赖(
npm install
或yarn
完成后)后,把修复代码加上。
在 package.json
配置文件 scripts
下添加 postinstall
钩子,完成依赖安装后运行 postinstall
中的代码。 package postinstall 使用说明
{
// ...
"scripts": {
// 添加下面这行
"postinstall": "node react-native-textinput-patch.js"
},
// ...
}
在 package.json
同级目录下创建 react-native-textinput-patch.js
文件,作用就是为了添加那几行修复代码
const fs = require('fs');
const packageJSON = JSON.parse(fs.readFileSync(`./package.json`));
if(packageJSON.dependencies['react-native'] !== '0.62.2') {
console.log('\x1B[33m%s\x1B[0m', 'WARNING: please delete react-native-textinput-patch.js file, and remove postinstall hook script.')
return;
}
let filePath = './node_modules/react-native/Libraries/Text/TextInput/Multiline/RCTUITextView.m';
let oldCode =
`- (void)setDefaultTextAttributes:(NSDictionary<NSAttributedStringKey, id> *)defaultTextAttributes
{
_defaultTextAttributes = defaultTextAttributes;
self.typingAttributes = defaultTextAttributes;
[self _updatePlaceholder];
}`;
let newCode =
`- (void)setDefaultTextAttributes:(NSDictionary<NSAttributedStringKey, id> *)defaultTextAttributes
{
if ([_defaultTextAttributes isEqualToDictionary:defaultTextAttributes]) {
return;
}
_defaultTextAttributes = defaultTextAttributes;
self.typingAttributes = defaultTextAttributes;
[self _updatePlaceholder];
}`;
console.log('\x1B[32m%s\x1B[0m', 'patching file: ' + filePath)
fs.writeFileSync(filePath, fs.readFileSync(filePath, 'utf8').replace(oldCode, newCode));
filePath = './node_modules/react-native/Libraries/Text/TextInput/Singleline/RCTUITextField.m';
oldCode =
`- (void)setDefaultTextAttributes:(NSDictionary<NSAttributedStringKey, id> *)defaultTextAttributes
{
_defaultTextAttributes = defaultTextAttributes;
[super setDefaultTextAttributes:defaultTextAttributes];
[self _updatePlaceholder];
}`;
newCode =
`- (void)setDefaultTextAttributes:(NSDictionary<NSAttributedStringKey, id> *)defaultTextAttributes
{
if ([_defaultTextAttributes isEqualToDictionary:defaultTextAttributes]) {
return;
}
_defaultTextAttributes = defaultTextAttributes;
[super setDefaultTextAttributes:defaultTextAttributes];
[self _updatePlaceholder];
}`;
console.log('\x1B[32m%s\x1B[0m', 'patching file: ' + filePath)
fs.writeFileSync(filePath, fs.readFileSync(filePath, 'utf8').replace(oldCode, newCode));
console.log('\x1B[32m%s\x1B[0m', 'TextInput was patched!')
以上添加完成后,删除 node_modules
文件夹,重新安装依赖就可以了。
其他解决方案
相同原理,一样是依赖安装完成后更新修正代码,懒得自己写代码,就直接安装这个: react-native-cjk-textinput-patch
我要留言