如何在反应导航中每次输入都获得焦点

时间:2019-01-22 02:28:35

标签: react-native react-navigation

我使用React导航TabNavigator,我希望每次用户进入第二个选项卡时,屏幕上的一个TextInput都会获得焦点,键盘会弹出

4 个答案:

答案 0 :(得分:2)

您可以为此使用refsreact navigation lifecycle

<p> <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>

答案 1 :(得分:1)

这可能对您有帮助

$ ls -l Xcode
-rwxr-xr-x  1 root  wheel  44416 Apr 11 13:40 Xcode*

Xcode事件将在每次显示视图时触发(例如iOS中的this.viewDidAppearListener = this.props.navigation.addListener('didFocus', (payload) => this._viewDidAppear(payload)); ),因此您可以手动对文本输入执行didFocus

答案 2 :(得分:0)

最简单的方法是将“ autoFocus”添加到您的textInput 像这样:

 <TextInput 
       placeholder="Type any activity name"
       placeholderTextColor="lightgray"
       ...
       ref="textInput"
       autoFocus />

答案 3 :(得分:0)

对于react-navigation@3.X.X,请使用 navigation.addListener .focus()

class AutoFocusedTextInput extends React.Component {
  state = {
    text: '',
  }

  componentDidMount() {
    this.props.navigation.addListener('didFocus', payload => {this.textInput.focus()})
  }

  componentWillUnmount() {
    didFocusSubscription.remove();
  }

  render() {
    return (
      <View>
        <TextInput
          ref={(component) => this.textInput = component}
          autoFocus={true}
          placeholder="Start typing"
          onChangeText={(text) => this.setState({text})}
          value={this.state.text}
        />
      </View>
    )
  }
}

参考:
https://reactnavigation.org/docs/3.x/navigation-prop#addlistener---subscribe-to-updates-to-navigation-lifecycle