映射React Native

时间:2018-02-02 07:54:08

标签: react-native

我正在创建react-native mobile个应用。我有一个带有一些值的数组。我想将数组的值设置为输入字段。我在字段中增加了值,但我无法更新这些值。我已将值设置为如下的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>
    ))
  }
}

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

3 个答案:

答案 0 :(得分:1)

我建议你将输入容器移动到单独的类中,它的方法更好,每个组件都会处理自己的状态。它易于操作,性能也更好。

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类中创建这些函数(getValue&amp; setValue)。

溶液

以下是您的查询的解决方案。您需要安装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})
}

答案 1 :(得分:0)

您的输入值设置为this.state.qty[Index]['qty']。要在文本编辑中更改它,您可以这样做。您不需要绑定该函数,而是使用这样的箭头函数。

onChangeText={ (newValue) => {
    this.setState({ <your-input-value-state>:newValue })
}}

答案 2 :(得分:0)

您必须在Input事件中单独更新每个onChange的值。

Input替换为此

<Input value={this.state.qty[Index]['qty']}
       onChange={this.handleChangeInput.bind(this, Index)}
       style={{width:40,height:40,textAlign:'left'}}
/>

并在调用Index时使用event相应地更新状态

handleChangeInput(index, value){
    let {qty} = this.state;
    let qty_update = qty.slice();
    qty_update[index]['qty']  = value;
    this.setState({qty: qty_update});
}
相关问题