Focus style for TextInput in react-native

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

    Nader Dabit´s pointed me to do something similar -- using the state for styles -- but I think it can be done in a cleaner way if you created separate styles for the focused and unfocused style and pass only the style ID as follows:

    getInitialState() {
      return { style: styles.textinput_unfocused }
    }
    onFocus() {
      this.setState({ style: styles.textinput_focused })
    }
    onBlur() {
      this.setState({ style: styles.textinput_unfocused })
    }
    

    in render -- referencing by styleID in this.state.style, note how the different styles are passed as an Array:

     this.onBlur() }
      onFocus={ () => this.onFocus() }
      style={ [styles.textinput, this.state.style] }  />
    

    + your stylesheet à la carte:

    textinput_focused: {
      backgroundColor: 'red',
      color: 'white'
    }
    textinput_unfocused: {
      backgroundColor: 'green'
    }
    

提交回复
热议问题