【发布时间】:2020-04-28 08:01:47
【问题描述】:
注意:我知道有很多类似的问题,我已经尝试对它们实施答案,但没有成功。
在我的 React Native 应用程序中,我有一个接受有限数量的自定义文本输入组件的表单。当用户按下返回按钮时,我正在尝试找到一种解决方案来移动到下一个输入。我尝试了一些软件包,但似乎没有一个与 Android 配合得非常好。我也尝试过使用 refs,但似乎运气不佳(注意表单是一个功能组件)。当我尝试在浮动标签组件中访问它时,它一直返回未定义。
自定义组件:
<FloatLabelTextInput
value={billingFirstName}
onChangeText={newText => setBillingFirstName(newText)}
autoCorrect={false}
style={globalStyles.textInput}
label="Billing First Name"
/>
浮动标签文本输入组件呈现文本输入(带有基于材质的浮动标签)。
import React, { Component } from 'react';
import {
Alert,
Button,
View,
TextInput,
Animated,
Image,
TouchableOpacity,
} from 'react-native';
import colors from '../utils/colors';
export default class FloatLabelTextInput extends Component<Props> {
static defaultProps = {
editable: true,
showHelp: false,
};
state = {
isFocused: false,
};
componentDidUpdate() {
Animated.timing(this.animatedIsFocused, {
toValue: this.state.isFocused || this.props.value !== '' ? 1 : 0,
duration: 200,
}).start();
}
handleFocus = () => {
this.setState({ isFocused: true });
if (this.props.onFocus) {
this.props.onFocus();
}
};
handleBlur = () => this.setState({ isFocused: false });
focus() {
this.ref.focus();
}
blur() {
this.ref.blur();
}
updateCursorPosition() {
this.ref.setNativeProps({
selection: { start: 0, end: 0 },
});
this.ref.setNativeProps({
selection: {
start: this.props.value.length,
end: this.props.value.length,
},
});
}
showAlert = helpText => {
Alert.alert(helpText.title, helpText.body, [{ text: helpText.button }], {
cancelable: helpText.cancelable,
});
};
render() {
const { label, style, isShowingRightAccessory, ...props } = this.props;
const labelStyle = {
position: 'absolute',
left: 0,
top: this.animatedIsFocused.interpolate({
inputRange: [0, 0.9],
outputRange: [15, 0],
}),
fontSize: this.animatedIsFocused.interpolate({
inputRange: [0, 1],
outputRange: [18, 14],
}),
};
return (
<View
style={[
this.props.style,
{ paddingTop: 18, opacity: this.props.editable ? 1 : 0.5 },
]}>
<Animated.Text
style={[
labelStyle,
{
color: colors.lightBlue,
},
]}
allowFontScaling={false}>
{label}
</Animated.Text>
<TextInput
{...props}
caretHidden={false}
underlineColorAndroid="transparent"
ref={c => {
this.ref = c;
}}
selectionColor={colors.lightBlue}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
blurOnSubmit
allowFontScaling={false}
/>
{this.props.showHelp && (
<TouchableOpacity
style={{
marginTop: 20,
position: 'absolute',
alignSelf: 'flex-end',
}}
onPress={() => this.showAlert(this.props.helpText)}>
<Image
style={{
height: 15,
width: 15,
}}
source={require('../../assets/icon_Tooltip.png')}
/>
</TouchableOpacity>
)}
<View style={{ height: 1, width: '100%', backgroundColor: 'white' }} />
</View>
);
}
}
我的猜测是我想实现一个基于 ref 的解决方案,我正在寻找有关如何使用自定义文本组件来实现这一点的建议
【问题讨论】:
-
我想这基本上就是你要找的东西:stackoverflow.com/questions/32748718/…
-
@TravisJames 这就是我在尝试的第一个位中所指的内容,它一直返回未定义,我认为这是因为我使用了自定义组件
标签: reactjs react-native ref