Focus style for TextInput in react-native

后端 未结 7 1455
小鲜肉
小鲜肉 2020-12-05 17:56

In React Native, how do you change the style of a textInput when it gets focus? Say I have something like

class MyInput extends Component {
             


        
相关标签:
7条回答
  • 2020-12-05 18:49

    You can achieve this by passing in the onFocus and onBlur events to set and unset styles when focused and blurred:

      onFocus() {
        this.setState({
            backgroundColor: 'green'
        })
      },
    
      onBlur() {
        this.setState({
          backgroundColor: '#ededed'
        })
      },
    

    And then, in the TextInput do this:

    <TextInput 
        onBlur={ () => this.onBlur() }
        onFocus={ () => this.onFocus() }
        style={{ height:60, backgroundColor: this.state.backgroundColor, color: this.state.color }}  />
    

    I've set up a full working project here. I hope this helps!

    https://rnplay.org/apps/hYrKmQ

    'use strict';
    
    var React = require('react-native');
    var {
      AppRegistry,
      StyleSheet,
      Text,
      View,
      TextInput
    } = React;
    
    var SampleApp = React.createClass({
    
      getInitialState() {
        return {
            backgroundColor: '#ededed',
          color: 'white'
        }
      },
    
      onFocus() {
            this.setState({
            backgroundColor: 'green'
        })
      },
    
      onBlur() {
        this.setState({
          backgroundColor: '#ededed'
        })
      },
    
      render: function() {
        return (
          <View style={styles.container}>
           <TextInput 
            onBlur={ () => this.onBlur() }
            onFocus={ () => this.onFocus() }
            style={{ height:60, backgroundColor: this.state.backgroundColor, color: this.state.color }}  />
          </View>
        );
      }
    });
    
    var styles = StyleSheet.create({
      container: {
        flex: 1,
        marginTop:60
      }
    });
    
    AppRegistry.registerComponent('SampleApp', () => SampleApp);
    
    0 讨论(0)
提交回复
热议问题