我创建了一个浮动的标签文本框,其中onFocus和onBlur道具用于文本框。 一切工作正常,但出现一个问题,就是在文本框上键入一些文本后标签没有向上移动。以下是我的代码:
export class FloatingLabelInput extends Component {
state = {
isFocused: false
};
render() {
const { label, ...props } = this.props;
const { isFocused } = this.state;
const labelStyle = {
position: "absolute",
left: 0,
top: !isFocused ? 18 : 0,
fontSize: !isFocused ? 20 : 14,
color: !isFocused ? "#000" : "#102657"
};
return (
<View style={{ paddingTop: 10 }}>
<Text style={labelStyle}>{label}</Text>
<TextInput
{...props}
onBlur={(value) => {
if (value.length!=0) {
this.setState({ isFocused: false });
} else {
this.setState({ isFocused: true });
}
}}
onFocus={(value) => {
if (value.length!=0) {
this.setState({ isFocused: true });
}
else{
this.setState({ isFocused: false });
}
}}
>
{this.props.value}
</TextInput>
</View>
);
}
}
答案 0 :(得分:0)
下面是一个浮动TextInput,其灵感来自在线文章。 (https://goshakkk.name/floating-label-input-rn-animated/)
FloatingLabelInput.js
import React from 'react';
import { View, TextInput, Animated } from 'react-native';
export class FloatingLabelInput extends React.Component {
state = {
isFocused: false,
}
componentWillMount() {
this._animatedLabelValue = new Animated.Value(this.props.value === '' ? 0 : 1);
}
handleFocus = () => this.setState({ isFocused: true });
handleBlur = () => this.setState({ isFocused: false });
componentDidUpdate() {
Animated.timing(this._animatedLabelValue, {
toValue: (this.state.isFocused || this.props.value !== '') ? 1 : 0,
duration: 200,
}).start();
}
render() {
const { label, ...props } = this.props; //Here is the text for the label
const { isFocused } = this.state;
const labelStyle = {
position: 'absolute',
left: 0,
top: this._animatedLabelValue.interpolate({
inputRange: [0, 1],
outputRange: [this.props.labelFontSize*0.67, -this.props.labelFontSize*0.05],
}),
fontSize: this._animatedLabelValue.interpolate({
inputRange: [0, 1],
outputRange: [this.props.labelFontSize, this.props.labelFontSize*0.7],
}),
color: this._animatedLabelValue.interpolate({
inputRange: [0, 1],
outputRange: ['#aaa', '#000'],
}),
fontWeight: this.props.bold ? 'bold' : 'normal'
}
const containerStyle = {
paddingTop: 18,
marginTop: 20
}
return (
<View style={{paddingTop: 18}}>
<Animated.Text>
{label}
</Animated.Text>
<TextInput
{...props}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
/>
</View>
)
}
}