react-native - 映射 React Native 时更新输入值

标签 react-native

我正在创建react-native移动应用程序。我有一个包含一些值的数组。我想将数组的值设置到输入字段中。我在字段中添加了值,但无法更新这些值。我已在 qty 变量中设置了值,如下所示:

constructor(props) {
  super(props);
  this.state = {
    qty:[],
  }
}

componentWillMount() {
  var ids = [];
  this.props.data.map((dataImage,Index) => {
    dataImage['pro-name'] != undefined && (
      ids.push({'qty':dataImage['pro-qty']})    
    )
  })

  this.setState({qty:ids})
}

render() {
  return {
    this.props.data.map((dataImage,Index)=>(
      <View key={Index} style={productStyle.cartview}>
        {dataImage['pro-name'] && (
          <View style={productStyle.cartmain}>
            <Input value={this.state.qty[Index]['qty']} onChange={this.handleChangeInput.bind(this)} style={{width:40,height:40,textAlign:'left'}} />
          </View>
        )}
      </View>
    ))
  }
}

它在输入字段中正确显示值,但我无法在字段中输入任何内容来更新值。我能为此做什么

最佳答案

我建议您将输入容器移动到单独的类中,这是更好的方法,并且每个组件将处理自己的状态。它易于处理并且也会带来更好的性能。

components = []

render() {
  return this.props.data.map((item, index) => (
    <CustomComponent data={item} index={index} ref={(ref) => this.components[index] = ref} />
  ))
}

然后您可以从其引用中获取子 (CustomComponent) 值。

this.components[index].getValue()
this.components[index].setValue('Value');

您需要在 CustomComponent 类中创建这些函数 (getValuesetValue)。

解决方案

这是您的查询的解决方案。您需要安装 lodash 或找到其他解决方案来制作新的副本 qty

<Input onChangeText={(text) => this.handleChangeText(text, index)} />

handleChangeText = (text, index) => {
  const qty = _.cloneDeep(this.state.qty);
  qty[index] = {
    qty: text
  }
  this.setState({qty})
}

关于react-native - 映射 React Native 时更新输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48578127/

相关文章:

javascript - 帕霍 MQTT : Possible importing error?

reactjs - React Native iOS 中的响应式布局

firebase - 如何模拟/ stub react-native-firebase?

reactjs - 使用 CRNA 进行社交共享(创建 React Native 应用程序)

android - 在 React Native 中从 Asyncstorage 数据库获取数据的最佳实践

react-native - react native : Cannot vertically align an image to bottom of the screen

ios - 如何在 FlatList 中使用 KeyboardAvoidingView?

javascript - 值不能从 ReadableNativeMap 转换为 double

javascript - Undefined 不是评估 this.state 的对象。*

javascript - React-Native 渲染多个图像