Change style when TextInput onFocus and onBlur.React-Native

元气小坏坏 提交于 2020-08-26 07:07:53

问题


I have 40 TextInput in 5 page and need to change input text color onfocus:'white' and onBlur:'gray' I know how make it for single input.But I need for multiple input

<TextInput 
  clearTextOnFocus={true}
  keyboardType="number-pad"
  style={[this.state.isFocused?styles.inputOnFocus:styles.input]}
  onChangeText={v=>handleInput('value',v)}
  value={this.state.value}
  onFocus={()=>this.setState({isFocused:true})}
  onBlur={()=>this.setState({isFocused:false})}

/>

回答1:


You can simply give each one of the Inputs an ID and use that one to know which ID is focused:

<TextInput 
  clearTextOnFocus={true}
  keyboardType="number-pad"
  style={[this.state.FocusedItem === "TextInput1"? styles.inputOnFocus : styles.input]}
  onChangeText={v=>handleInput('value',v)}
  value={this.state.value}
  onFocus={()=>this.setState({FocusedItem: "TextInput1"})}
  onBlur={()=>this.setState({FocusedItem: ""})}
/>

In a .map() function it could be like:

arr.map( (item, index) => { 
   let ID = "TextInput"+index
   return (
       <TextInput 
          clearTextOnFocus={true}
          keyboardType="number-pad"
          style={[this.state.FocusedItem === ID? styles.inputOnFocus : styles.input]}
          onChangeText={v=>handleInput('value',v)}
          value={this.state.value}
          onFocus={()=>this.setState({FocusedItem: ID})}
          onBlur={()=>this.setState({FocusedItem: ""})}
       />
   ) 
})

This is just for focus purpose. If the code stays like this, all inputs will have the same value




回答2:


Set up your text inputs and their styles in a component. Then use state in the component to control your styles.

const [focus, setFocus] = useState(false);

<TextInput
    style={focus ? styles.inputOnFocus : styles.inputOnBlur}
    onFocus={() => setFocus(true)}
    onBlur={() => setFocus(false)}
/>

Styles:

const styles = StyleSheet.create({
    inputOnFocus: { borderColor: '#C0C0C0' },
    inputOnBlur: { borderColor: '#4b6cd5' }
});


来源:https://stackoverflow.com/questions/59047142/change-style-when-textinput-onfocus-and-onblur-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!