如何使用 TextInput isFocused() 方法

新手上路,请多包涵

根据 React Native API 文档中的此链接: https ://facebook.github.io/react-native/docs/0.59/textinput#isfocused

TextInput 组件有一个名为 isFocused() 的方法。我将如何访问此方法?我必须使用参考吗?

此外,我已经知道我可以通过使用 onFocus 道具并设置状态管理器和函数来实现相同的效果,以根据 onFocus 更改输入的状态。但是,我很好奇我将如何使用这些组件方法,因为其他组件中也有其他方法。

我试过用这个

<TextInput onChangeText={this.handleText} style={(this.isFocused()) ? styles.input : styles.lame} placeholder="Names"/>

但看起来我可能不得不使用 ref 因为它似乎没有定义,即使该方法应该是该组件的一部分。

原文由 Chris Matthews 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 467
2 个回答

isFocused() 应该在引用 TextInput 时调用。

 import React, {useEffect, useRef} from 'react';
import {TextInput, BackHandler} from 'react-native';

function SearchBar() {
  const textInputReference = useRef(null);
  useEffect(() => {
    let backhandler = BackHandler.addEventListener(
      'hardwareBackPress',
      function() {
        if (textInputReference.current.isFocused()) {
          textInputReference.current.blur();
          return true;
        }
        return false;
      },
    );
    return () => {
      backhandler.remove();
    };
  }, []);
  return (
        <TextInput ref={textInputReference} />
  );
}

export default SearchBar;

原文由 a-c-sreedhar-reddy 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用状态来处理输入焦点,如果您有多个输入也需要焦点状态,只需为其创建多个状态即可。

 class MyComponent extends React.Component {

   state = { isFocused: false }

   handleInputFocus = () => this.setState({ isFocused: true })

   handleInputBlur = () => this.setState({ isFocused: false })

   render() {
      const { isFocused } = this.state

      return (
        <View>
          <TextInput
            onFocus={this.handleInputFocus}
            onBlur={this.handleInputBlur}
            style={ isFocused ? styles.input : styles.lame}
          />
          <Text>Hello World</Text>
        </View>
      )
   }
}

原文由 Hung Nguyen 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题