Focus style for TextInput in react-native

后端 未结 7 1460
小鲜肉
小鲜肉 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:44

    Hey guys I kinda used everyones idea :p

    @Felix gave me an idea that might be perhaps even cleaner. (I would have loved to not have included state though on this static component, just to change styling... But I am to new to this to figure that out.

    here was my solution:

    import React, { Component } from 'react';
    import { StyleSheet, TextInput } from 'react-native';
    
    class TxtInput extends Component {
      constructor(props) {
        super(props);
        this.state = {
          style: {},
        };
      }
    
      onFocus = () => {
        const state = { ...this.state };
        state.style = {
          borderStyle: 'solid',
          borderColor: '#e74712',
        };
    
        this.setState(state);
      }
    
      onBlur = () => {
        console.log('on ONBLUR')
        const state = { ...this.state };
        state.style = {};
    
        this.setState(state);
      }
    
      render = () =>  this.onFocus()} onBlur={() => this.onBlur()} />;
    }
    
    const styles = StyleSheet.create({
      input: {
        color: '#000000',
        fontFamily: 'MuseoSans 700 Italic',
        fontSize: 22,
        borderRadius: 34,
        borderStyle: 'solid',
        borderColor: 'transparent',
        borderWidth: 5,
        backgroundColor: '#ffffff',
        textAlign: 'center',
        width: '25%',
     },
    });
    
    export default TxtInput;
    

    I added the style into an array, have all the actual input styling done on the first property of the array and the second one the nit picking of the focus and blue.

    Hope it helps

提交回复
热议问题