问题
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