我正在创建一个组件,该组件应在我的应用中用作React Native TextInput
的包装。我创建了一个可见性切换项,以显示或不显示密码。当我更改secureTextEntry
道具时,我的TextInput
的插入符号位置重置为0。
我尝试使用状态存储插入符位置和在TextInput
组件上的引用来解决该问题,以在切换securedTextEntry
道具之后调用该setNativeProps。
这是我的组件:
export default class AppTextInput extends React.Component<Props, State>
{
static defaultProps = {
defaultValue: '',
icon: '',
keyboardType: 'default',
secureTextEntry: false,
style: {},
styleTI: {},
};
state = {
isPasswordHidden: true,
// State used to track cursor position
selection: {
start: 0,
end: 0,
},
};
// Update state when selection changes
handleSelectionChange = ({
nativeEvent: { selection },
}: {
nativeEvent: { selection: { start: number, end: number } },
}) => {
this.setState(() => ({ selection }));
};
tooglePasswordVisibility = () => {
this.setState(prevState => ({
isPasswordHidden: !prevState.isPasswordHidden,
}));
// Set the caret position back to its previous location and not 0
this.textInputRef.setNativeProps({
selection: { start: this.state.selection.start, end: this.state.selection.end },
});
};
// Reference of the TextInput (typed with Flow)
textInputRef: React.ElementRef<TextInput>;
render() {
const {
callbackFromParent,
defaultValue,
icon,
keyboardType,
placeholder,
secureTextEntry,
style,
styleTI,
} = this.props;
const { isPasswordHidden, selection } = this.state;
return (
<View style={{ ...styles.textInputView, ...style }}>
<Icon color="#000" name={icon} size={20} style={styles.icon} />
<TextInput
// Reference of the TextInput
ref={textInputRef => (this.textInputRef = textInputRef)}
defaultValue={defaultValue}
keyboardType={keyboardType}
onChangeText={text => callbackFromParent(text)}
// Method to handle selection changes
onSelectionChange={this.handleSelectionChange}
placeholder={placeholder}
placeholderTextColor="black"
secureTextEntry={secureTextEntry && isPasswordHidden}
// State to use for the selection
selection={selection}
style={{ ...styles.input, ...styleTI }}
underlineColorAndroid="transparent"
/>
{secureTextEntry && (
<Icon
color="#000"
name={isPasswordHidden ? 'eye' : 'eye-off'}
onPress={this.tooglePasswordVisibility}
size={20}
style={styles.icon}
/>
)}
</View>
);
}
}
答案 0 :(得分:0)
我在Facebook React Native GitHub上碰到了某人的公关,为实现0.59.5版本而进行了精心挑选!错误已修复!