【问题标题】:When text input is filled, button doesn't submit填充文本输入时,按钮不提交
【发布时间】:2018-03-23 22:54:27
【问题描述】:

当上述两个文本字段均未填充时,将调用按钮的 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>
);
}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您是否尝试过使用

    e.preventDefault()
    

    ?

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

    【讨论】:

      【解决方案2】:
      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>
        );
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-20
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多