【问题标题】:React-Native TextInput that edits dynamic object key:values编辑动态对象 key:values 的 React-Native TextInput
【发布时间】:2018-02-14 18:13:54
【问题描述】:

我正在使用 Redux 开发 React-Native。其中一个组件根据传递给它的道具中的对象中的元素呈现一系列 TextInput,该道具是从应用程序早期的 API 读取的。

我希望能够编辑该值并使其在状态中更新。对象的键、值和长度都是动态的。我所有的 redux 操作和 reducer 都可以工作,并且我的组件正在正确接收它的 props,所以我将尝试将其归结为一个非常简单的示例。为了说明我的问题,假设组件在它的 props 中接收到这个对象:

 item:{
   type: monitor,
   make: HP,
   tag_number: 005
 }

我的组件的渲染方法创建并显示文本输入:

render(){
   var item_views = []
   for(index in this.props.item) {
     item_views.push(
          <View key={index} style={styles.rowContainer}>
          <Text style={styles.label}>{index} : </Text>
          <TextInput 
             style={styles.input_box}
             onSubmitEditing={(text) => this._update(index, text)}
             defaultValue={this.props.item[index].toString()}
             placeholder={index}>
          </TextInput>
          </View>
     )
   }
   return (
     <View>
     {item_views}
     </View>
   )
 }

 _update(index, text){
    //This is where I dispatch the action to change the value of "item[index]" to "text"
 }

这个几乎有效,除了“索引”,它总是正确显示在渲染方法中的各个相应 TextInputs 中,在“_update”函数中总是解析为对象中的顶部键,即本例中的“类型”,无论我编辑哪个文本输入。如何通过 textinput 的 onSubmitEditing 函数将正确的索引传递给我的更新函数?

【问题讨论】:

    标签: react-native redux


    【解决方案1】:

    尝试在你的 for 循环中使用“let”

    for(let index in this.props.item) {
         item_views.push(
              <View key={index} style={styles.rowContainer}>
              <Text style={styles.label}>{index} : </Text>
              <TextInput 
                 style={styles.input_box}
                 onSubmitEditing={(text) => this._update(index, text)}
                 defaultValue={this.props.item[index].toString()}
                 placeholder={index}>
              </TextInput>
              </View>
         )
       }
    

    在您的情况下 index 和 item_views 都是全局对象,因此 index 在您的 item_views 中始终具有最终值(无论它是什么)

    【讨论】:

    • 在哪里使用这个code-sn-p?内部渲染它不能正常工作?
    【解决方案2】:

    你可以使用函数式编程:

    render(){
       const { items } = this.props;
       return (
         <View>
         {items.map((el,index) => (
            <View key={some_id} style={styles.rowContainer}>
              <Text style={styles.label}>{index} : </Text>
              <TextInput 
                 style={styles.input_box}
                 onSubmitEditing={(text) => this._update(index, text)}
                 defaultValue={el.toString()}
                 placeholder={index}>
              </TextInput>
            </View>
         ))}
         </View>
       )
     }
    
     _update(index, text){
        //This is where I dispatch the action to change the value of "item[index]" to "text"
     }
    

    不要在组件键处使用索引:https://reactjs.org/docs/lists-and-keys.html#keys

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      相关资源
      最近更新 更多