填写文本输入时,按钮不会提交

时间:2018-03-23 22:54:27

标签: react-native

当上面的文本字段都没有填满时,调用按钮的onPress函数。否则,我按下按钮,没有任何反应。我尝试将onPress更改为onPress={this.handleSubmit()},但在TextInput中的任何数据出现之前调用该函数并抛出错误。我也尝试过使用tcomb-form-native软件包,但问题仍然存在。当文本输入被填充时,我需要更改什么才能调用handleSubmit函数?

handleSubmit = () => {
  console.log('handle submit')
}    

render() {
return (
  <View style={styles.container}>
    <TextInput
      style={{height: 40}}
      placeholder="Your name"
      onChangeText={userName => this.setState({userName})}
    />
    <TextInput
      style={{height: 40}}
      placeholder="other name"
      onChangeText={otherName => this.setState({otherName})}
    />
    <Button
      title="Name"
      onPress={this.handleSubmit}
    />
  </View>
);
}

2 个答案:

答案 0 :(得分:0)

您是否尝试过使用

e.preventDefault()

handleSubmit = (e) => {
e.preventDefault()
  console.log('handle submit')
}  

答案 1 :(得分:0)

您可以尝试这样的事情:

constructor(props){
    super(props);
    this.state = {
        userName: '',
        otherName: ''
    };
}

handleSubmit = () => {
    // Check if any of them is empty then do nothing
    if(!this.state.otherName || !this.state.userName){return;}
    console.log('handle submit');
  }    

  render() {
  return (
    <View style={styles.container}>
      <TextInput
        style={{height: 40}}
        placeholder="Your name"
        onChangeText={userName => this.setState({userName})}
      />
      <TextInput
        style={{height: 40}}
        placeholder="other name"
        onChangeText={otherName => this.setState({otherName})}
      />
      <Button
        title="Name"
        onPress={this.handleSubmit}
      />
    </View>
  );
  }

快乐编码:)