onChange()上的两个函数

时间:2018-03-24 01:38:47

标签: react-native

我有一个TextInput:

<TextInput
  ref='edit'
  style={{height:60, borderColor:'gray', borderWidth:1, backgroundColor:'white', borderRadius:10, margin:30}}
  onChangeText={function(text){
    this.setState({busca: text}) //<<ERROR HERE
    if (this.state.busca.lenght >= 13){
      onSubmitEditing={() => this.props.navigation.navigate('Resultado', {busca: this.state.busca})}
  }
  }}
  onSubmitEditing={() => this.props.navigation.navigate('Resultado', {busca: this.state.busca})}
  autoFocus
/>

当我尝试执行两个函数时,收到错误

  

undefined不是函数

但如果我只放了一个函数onChangeText={(text) => this.setState({busca: text})},那么

2 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

<TextInput
  ref='edit'
  style={{height:60, borderColor:'gray', borderWidth:1, backgroundColor:'white', borderRadius:10, margin:30}}
  onChangeText={text => this._useText(text)}
  }}
  onSubmitEditing={() => this.props.navigation.navigate('Resultado', {busca: this.state.busca})}
  autoFocus
/>

创建一个可以执行任何操作的函数:

修改

_useText = text => {
   // Make use of text
   this.setState({ busca: text});
   // UPDATE: You shouldn't use the state variable instantly after you set it or you will get an error/old value, reason: the state is not updated yet.
   if(text.length >= 13){
       this.props.navigation.navigate('Resultado', {busca: text})
   )
}

快乐编码:)

答案 1 :(得分:1)

你只能将一个处理函数传递给prop,所以只需在下面的组件中创建一个包装函数并调用它。

class App extends React.Component {
  handler(text) {
    this.setState({ busca: text })
    otherFunction()
  }

  render() {
    <TextInput
      ref='edit'
      style={{height:60, borderColor:'gray', borderWidth:1, backgroundColor:'white', borderRadius:10, margin:30}}
      onChangeText={this.handle.bind(this)}
      onSubmitEditing={() => this.props.navigation.navigate('Resultado', {busca: this.state.busca})}
      autoFocus
    />
  }
}