首页 > 解决方案 > 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>

)}

标签: react-native

解决方案


首先初始化你的变量

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"
      />

推荐阅读