在onFocus()上仅触发一个textInput

时间:2018-11-10 19:53:00

标签: react-native

每次我聚焦a或编辑它时,无论控制台是什么,我的console.log(“ triggered”)。

如何隔离onFocus()?谢谢。

    <TextInput
      placeholder="firstname"
      textContentType="name"
      selectTextOnFocus
      onChangeText={value => this._handleStateEdition("firstname", value)}
    />
    <TextInput
      placeholder="lastname"
      textContentType="familyName"
      selectTextOnFocus
      onFocus={console.log("triggered")}
      onChangeText={value => this._handleStateEdition("lastname", value)}
    />

1 个答案:

答案 0 :(得分:0)

它们已经被隔离了,但是您可以添加autofocus = false,以使您的字段不会自动获得焦点,此外,我从未使用过的另一种方法是使用引用。

自动对焦方法

<TextInput
  placeholder="firstname"
  textContentType="name"
  selectTextOnFocus
  autoFocus={false}
  onChangeText={value => this._handleStateEdition("firstname", value)}
/>
<TextInput
  placeholder="lastname"
  textContentType="familyName"
  selectTextOnFocus
  autoFocus={false}
  onFocus={console.log("triggered")}
  onChangeText={value => this._handleStateEdition("lastname", value)}
/>

通过引用

<TextInput
  placeholder="firstname"
  textContentType="name"
  selectTextOnFocus
  autoFocus={false}
  ref={r=>this.first = r}
  onChangeText={value => this._handleStateEdition("firstname", value)}
/>
<TextInput
  placeholder="lastname"
  textContentType="familyName"
  selectTextOnFocus
  autoFocus={false}
  onFocus={console.log("triggered")}
  onChangeText={value => this._handleStateEdition("lastname", value)}
  ref={r=>this.last = r}
/>

在您的componentDidMount内部并监听onFocus事件

componentDidMount(){
this.first.onFocus = ()=>{
 //some function
}
this.last.onFocus = ()=>{
 //some function
}
}