【问题标题】:How to focus to text input without using ref?如何在不使用 ref 的情况下专注于文本输入?
【发布时间】:2017-04-09 13:25:26
【问题描述】:

我尝试过使用焦点和自动对焦。使用 React Native 0.43 示例简单场景

<ListItem
 title="Username"
 textInput={true}
 textInputValue={this.state.userName}
 textInputSecureTextEntry={false}
 textInputOnChangeText={this
 .bindData
 .bind(this, 'userName')}
 textInputAutoFocus={this.state.userNameAutoFocus}
 textInputFocus={this.state.userNameFocus}
 textInputKeyboardType="default"
 textInputPlaceHolder="Type your Username Here"
 textInputContainerStyle={styles.inputFormStyle}
 textInputOnSubmitEditing={this
 .nextFormComponent
 .bind(this, 'userPassword')}
 textInputReturnKeyType="next" /> 

Source Code Source Code NPM

【问题讨论】:

  • 请编辑您的问题,添加您有问题的代码部分。当您为 300 行代码添加一个链接时,没有人可以帮助您而不具体说明问题所在。
  • 添加了更简单的代码来理解问题。

标签: javascript react-native


【解决方案1】:
constructor(props) {
  super(props);
  this.state = { 
    textInputFocus:true
  };
}

render() {
 <View>
   <TextInput autoFocus={this.state.textInputFocus} />
 </View>
} 

试试这个代码。

【讨论】:

  • 我的原始代码使用与上面相同但无法正常工作。 &lt;ListItem textInputAutoFocus={this.state.userNameAutoFocus} textInputFocus={this.state.userNameFocus} textInputReturnKeyType="next"&gt;&lt;/ListItem&gt;
【解决方案2】:

你可以试试:

class App extends React.Component{
  componentDidMount(){
    this.nameInput.focus();
  }
  render() {
    return(
      <View>
        <input defaultValue="Won't focus"/>
        <input ref={(input) => { this.nameInput = input; }}   defaultValue="will focus"  />
      </View>
    );
  }
}

【讨论】:

  • 我不想更改 npm 源文件。当我将 ref 放在源 npm 时,问题就开始了,它会说错误无状态函数不应该有 refs。上面可能是我写回上面的 npm 源文件的最后选择。
猜你喜欢
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
  • 2016-12-05
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 2011-11-24
相关资源
最近更新 更多