反应本地-动态更新样式表值

时间:2018-09-18 06:57:06

标签: react-native stylesheet

我想更新样式表属性“ top”的值。当前是“ 25”,我想将值更改为“ 0”或其他。实际上,一旦用户单击“ TextInput”,我想将其存档,“ Text”将移至“ TextInput”的顶部。

import React, {Component} from 'react';
import {View, Text, TextInput, StyleSheet } from 'react-native';

export default class InputBoxComponent extends Component{
  constructor(props){
    super(props);
    this.state = {
      'labelPosition':25
    }
  }

  onFoucusHandler = () => {
    this.state.labelPosition = 0
  }

  onBlurHandler = () => {
    this.state.labelPosition = 25
  }

  render(){
    return(
      <View style={styles.container}>
        <Text style={{
          'color':'#7b858e',
          'fontSize':12,
          'top':this.state.labelPosition
        }}>{this.props.label}</Text>
        <TextInput style={styles.input} onFocus={this.onFoucusHandler} onBlur={this.onBlurHandler}/>
      </View>
    )
  }
}

InputBoxComponent.defaultProps = {
  'label':'Label',
  'labelPosition': 25
}

const styles = StyleSheet.create({
  container:{
    paddingBottom: 10,
    paddingTop: 10
  },
  input:{
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
    paddingTop: 5,
    paddingBottom: 5,
    fontSize: 16
  }
})

2 个答案:

答案 0 :(得分:0)

您必须为此尝试keyboardavoidingview

参考链接: https://facebook.github.io/react-native/docs/keyboardavoidingview

答案 1 :(得分:0)

您可以替换

this.state.labelPosition = 0 

this.setState({labelPosition:0})

还可以看看像Native Base这样的库 https://docs.nativebase.io/Components.html#floating-label-headref 我认为浮动标签可以完成您要实现的目标。