在焦点输入时更改按钮的颜色

时间:2018-12-19 08:40:13

标签: react-native

早上好,我尝试了一个带有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>

)}

2 个答案:

答案 0 :(得分:1)

首先初始化变量

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

答案 1 :(得分:0)

 style={{color: this.props.focused ? '#8B327C' :'#3F8B99'}}

尝试这样的事情