【问题标题】:Can I submit multiple tcomb forms with one onPress?我可以用一个 onPress 提交多个 tcomb 表单吗?
【发布时间】:2018-05-16 20:52:16
【问题描述】:

我正在构建一个 React Native 应用程序并为我的表单使用 tomb-form-native 库。在我的一个屏幕中,我循环遍历一组类型并为每种类型输出一个表单:

{my_types.map(ob =>
  <View key={++i}>
    <Text>{ob.type} #{ob.num}</Text>
    <Form 
      ref={(c) => { 
        this.form = {}
        this.form[ob.type] = c 
      }} 
      type={_formType(this, ob.type)} 
      options={_formOptions(ob.type)} 
      value={this.state.value}
      onChange={this.onChange.bind(this)}
    />
  </View>
)}

<TouchableHighlight style={styles.button} onPress={this.onPress.bind(this)}>
  <Text style={styles.buttonText}>Submit</Text>
</TouchableHighlight>

但是当我尝试在我的 onPress 函数中获取提交的值时,它不适用于多种类型。如果我只调用一次 getValue() 它适用于一种类型:

input = this.form['my_type'].getValue()
console.log(input) // I see in my debugger that it works.

但如果我尝试获取两种或更多类型的输入,我在日志中看不到任何内容...

input = this.form['my_type'].getValue()
console.log(input) // Nothing. It doesn't work.

input2 = this.form['my_other_type'].getValue()
console.log(input2) // Nothing here either.

是否可以使用 tcomb 库通过一个 onPress 提交多个表单?也许是我在 TouchableHighlight 的 onPress 属性中调用 onPress 函数的方式?

更新

这个简化的 onPress 函数表明我的表单 ref 仅在最后一次循环中工作。如果我的循环有两个项目...

  onPress() {

    let input = this.form[1]
    console.log(input) // Undefined.

    let input2 = this.form[2]
    console.log(input2) // Object.

  }

【问题讨论】:

    标签: javascript forms react-native tcomb-form-native tcomb


    【解决方案1】:

    这似乎是可能的。如果我使用数组来跟踪表单引用,它可以工作:

    this.form = []
    
    return (
    ...
    
    {a.map(ob =>
      <View key={++i} style={s}>
        <Text>{ob.type} #{ob.num}</Text>
        <Form 
          ref={(c) => { 
            this.form.push(c)
          }} 
          key={i}
          type={_formType(this, ob.type)} 
          options={_formOptions(ob.type)} 
          value={this.state.value}
          onChange={this.onChange.bind(this)}
        />
      </View>
    )}
    
    <TouchableHighlight style={styles.button} onPress={this.onPress.bind(this)}>
      <Text style={styles.buttonText}>Submit</Text>
    </TouchableHighlight>
    

    这是一个简化的 onPress...

    onPress() {
      let tF = this.form
      tF.forEach(function(f) {
        if (f) { // First two times through the loop, f is null, in my application.
          console.log(f.getValue()) // It works!
        }
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 2019-04-06
      • 2011-08-25
      相关资源
      最近更新 更多