【发布时间】:2019-07-02 00:05:27
【问题描述】:
我正在尝试分别管理 2 个输入的状态。这两个输入有一个浮动标签动画。当您专注于输入时,占位符会移到顶部,并且 onBlur 会回到原来的位置。
现在我有一个名为handleFocusAndBlur 的函数,我需要在其中实现该逻辑。现在这种行为有点奇怪,因为即使在一个输入中只有文本,如果你去一个空的输入,填写的输入的标签会回到原来的位置,这不应该是这样的。
这是我正在使用的组件:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, TextInput, Animated } from 'react-native';
import styles from '../../styles/SigningScreenStyles';
export default class SigningInputs extends Component {
state = { isFocused: false };
componentWillMount() {
this.animatedIsFocused = new Animated.Value(0);
}
componentDidUpdate() {
const { isFocused } = this.state;
Animated.timing(this.animatedIsFocused, {
toValue: isFocused ? 1 : 0,
duration: 200,
}).start();
}
// SEE THIS FUNCTION
handleFocusAndBlur = () => {
const { usernameLength, passwordLength } = this.props;
if (usernameLength || passwordLength) {
this.setState({ isFocused: false });
} else {
this.setState({ isFocused: true });
}
};
render() {
const { secureTextEntry, onChangeText, labelText } = this.props;
const labelStyle = {
position: 'absolute',
left: 0,
top: this.animatedIsFocused.interpolate({
inputRange: [0, 1],
outputRange: [10, -10],
}),
fontSize: this.animatedIsFocused.interpolate({
inputRange: [0, 1],
outputRange: [25, 14],
}),
color: this.animatedIsFocused.interpolate({
inputRange: [0, 1],
outputRange: ['black', 'gray'],
}),
};
return (
<>
<View style={styles.inputContainer}>
<Animated.Text style={labelStyle}>{labelText}</Animated.Text>
<TextInput
style={styles.inputs}
onChangeText={onChangeText}
onFocus={this.handleFocusAndBlur}
onBlur={this.handleFocusAndBlur}
blurOnSubmit
secureTextEntry={secureTextEntry}
propsLength
/>
</View>
</>
);
}
}
SigningInputs.defaultProps = {
secureTextEntry: false,
};
SigningInputs.propTypes = {
secureTextEntry: PropTypes.oneOfType([PropTypes.bool]),
onChangeText: PropTypes.func.isRequired,
labelText: PropTypes.oneOfType([PropTypes.string]).isRequired,
usernameLength: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
.isRequired,
passwordLength: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
.isRequired,
};
这就是我调用该组件的方式:
const { username, password } = this.state;
<SigningInputs
onChangeText={user => this.setState({ username: user })}
labelText="User Name"
usernameLength={username.length}
/>
<SigningInputs
onChangeText={pass => this.setState({ password: pass })}
secureTextEntry
labelText="Password"
passwordLength={password.length}
/>
当我只有一个输入时,这很容易,但现在有了 2 个输入,我发现我需要实现更多逻辑。
有人可以看一下吗?
【问题讨论】:
标签: javascript reactjs react-native ecmascript-6