【问题标题】:how can I clear Native-base Input text?如何清除基于本机的输入文本?
【发布时间】:2019-04-20 23:57:22
【问题描述】:

我试试这个

  <Input placeholder="search...."
         ref={(ref) => { this.SearchInput = ref; }}
         />
  <Button transparent onPress={this.clear}>
      <Ionicons name="ios-close" />
  </Button>

和功能:

  clear = () => {
    this.SearchInput.clear();
  }

我收到此错误:

this.SearchInput.clear() 不是函数

【问题讨论】:

  • 它适用于 TextInput 但不适用于 Input Native-base
  • 您没有使用 State 或 Redux 或任何状态管理器来控制您的文本输入?

标签: react-native native-base react-native-textinput


【解决方案1】:

这是运行代码,将ref更改为getRef并使用this.SearchInput._root.clear();而不是this.SearchInput.clear();

  clear = () => {
    this.SearchInput._root.clear();
  }
  render() {
    return (
      <Container>
        <Header />
        <Content>
          <Item floatingLabel>
            <Input placeholder="search...."
              getRef={(ref) => this.SearchInput = ref}
            />
          </Item>
          <Button onPress={this.clear}>
            <Ionicons name="ios-close" />
          </Button>
        </Content>
      </Container>
    );
  }

【讨论】:

  • ref和getRef有什么区别,
  • 对我来说,它只在我使用时才有效。在这个例子中用“ref”代替“getRef”
【解决方案2】:

我使用值和状态来实现这个功能

示例如下:

<Input
  value={ this.state.value }
  onChangeText={ this.onTextChange }
/>
<Button onPress={this.clear}>
  <Ionicons name="ios-close" />
</Button>

constructor上声明默认value的值

this.state = {
  value: ''
}

按如下方式监听 onTextChange,这确保 Input 上的值与我们插入时保持一致,而不是永远为空:

onTextChange = (value) => {
  this.setState({ value })
}

最后,关于clear 函数

clear = () => {
  this.setState({ value: '' })
}

只需将value 设置为空

【讨论】:

  • 很高兴我能帮上忙 ^_^
【解决方案3】:

我完全同意 Muhammad Hanzala 的观点,因为它在这方面对我有用,但有一个非常重要的例外,我必须这样做才能使其正常工作,确保像这样将文本输入的引用添加到您的构造函数:

constructor()
  {
    ...
   this.SearchInput = React.createRef();
  }

输入元素中的完整示例将如下所示...

<InputgetRef={(ref) => this.SearchInput = ref}/>

在你的构造函数中:

constructor()
  {
    ...
   this.SearchInput = React.createRef();
  }

最后你可以调用:

this.SearchInput._root.clear(); 

别忘了清除你的状态..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    相关资源
    最近更新 更多