react-native - onFocus 输入时改变 Button 的颜色
问题描述
早上好,我尝试了一个带有 react-native 的简单组件,它在 onFocus() 时更改按钮的颜色。我找不到如何更改颜色。这是我的组件。你有什么想法吗?
import React, {Component} from 'react';
import {
StyleSheet,Text, View, Button,
} from 'react-native';
export default class App extends Component {
render() {
return (
<View style={styles.inputContainer}>
<TextInput
maxHeight={200}
style={styles.textInput}
ref={(r) => {
this.textInputRef = r;
}}
placeholder={'Message'}
underlineColorAndroid="transparent"
onFocus={()=>{/*Here i awant to change the color of Button }}
testID={'input'}
/>
<Button color="transparent" id="ScanButton"
onPress={() => this.setState({text: 'Placeholder Text'})}
title="Scan Barcode"
/>
</View>
)}
解决方案
首先初始化你的变量
constructor(props) {
super(props);
this.state = {
isFocus: false
}
}
在您的 TextInput 中添加两个道具 onFocus() 和 onBlur()
<TextInput
maxHeight={200}
style={styles.textInput}
ref={(r) => {
this.textInputRef = r;
}}
placeholder={'Message'}
underlineColorAndroid="transparent"
onBlur={() => this.onBlur()}
onFocus={() => this.onFocus()}
testID={'input'}
/>
在你的类中添加两个方法来改变状态
onFocus() {
this.setState({
isFocus: true
})
}
onBlur() {
this.setState({
isFocus: false
})
}
你的按钮样式会是这样的
<Button
color={this.state.isFocus ? 'red' : 'green'}
id="ScanButton"
onPress={() => this.setState({text: 'Placeholder Text'})}
title="Scan Barcode"
/>
推荐阅读
- redirect - 仅重定向到裸域
- sql - 创建查询以从 B 和 C 为 A 中的每个项目返回 val
- ansible - 来自 github 操作秘密的 Ansible 变量
- javascript - 在打字稿中使用 JavaScript 库?
- angular - Observable 源对象被破坏时的内存泄漏
- android - Firebase 不存储数据。项目构建成功,在 Logcat 中没有错误
- javascript - 米利斯秒JS二分查找
- python - 将 CVXPY 向量与内部具有参数的数组进行比较的问题
- jquery - jquery在插入文本后立即设置插入焦点
- html - 在类上使用媒体查询