首页 > 解决方案 > 使用 react-native 表单提交

问题描述

抱歉,如果这是一个基本问题,但我似乎无法在我的 react-native 项目中找到替换 html 中的“表单”标签,所以我不知道在哪里调用我的“onSubmit”来发送我的搜索请求,因为 react-native 中的 'Form' 标签不接受 onSubmit 事件。那么我会用什么代替呢?这是我的代码,所以你有点知道它的样子

class SearchBar extends Component{
state = { term: '' }

  onFormSubmit(e) {
     e.preventDefault();
     console.log(this.state.term)
  }
 render(){
   return (
     <View style={styles.viewStyle}>
      <Text style=
       {styles.textStyle}>Search For Sick Pics.</Text>

  //so right here is what i dont know what to wrap my Textinput in, like in a react app we would wrap it in the "<form>" tag

        <TextInput 
        style={styles.inputStyle}
        type='text'
        placeholder='Search for Sick pics'
        value = {this.state.term}
        onChange = {event => this.setState({ term: event.target.value })}
        />   

  </View>
  )
 }
}

这是我的主要组件

     class MainPage extends Component {
      state = { images: [] }

    onSearchSubmit = (term) => {
      axios.get('https://api.unsplash.com/search/collections', {
       params: { query: term },
       headers: {
     Authorization: 
     'Client-ID jfkjasdhlkfjskdljfksdjfljasfasdj;fjaskdj'

    }
  }).then((response) => {
   console.log(response)
  })
}

 render() {
   return (
     <View>
         <SearchBar onSubmitEditing={this.onSearchSubmit}/>

     </View>
)

} }

标签: formsreact-nativeonsubmit

解决方案


尝试这个:

<TextInput 
  style={styles.inputStyle}
  type='text'
  placeholder='Search for Sick pics'
  value = {this.state.term}
  onChange = {event => this.setState({ term: event.target.value })}
  onSubmitEditing = {() => console.log(this.state.term)}
/>

或者你也可以调用你的'onFormSubmit'函数


推荐阅读