我正在创建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>
))
}
}它正确地将值显示在输入字段中,但我无法在字段中键入任何内容来更新值。我能为此做些什么?
发布于 2018-02-02 16:20:54
我建议您将输入容器移到单独的类中,这样更好,每个组件都会处理自己的状态。它易于处理,也会带来更好的性能。
components = []
render() {
return this.props.data.map((item, index) => (
<CustomComponent data={item} index={index} ref={(ref) => this.components[index] = ref} />
))
}然后,您可以从它的ref中获取子级(CustomComponent)值。
this.components[index].getValue()
this.components[index].setValue('Value');您需要在CustomComponent类中创建这些函数(getValue和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})
}https://stackoverflow.com/questions/48578127
复制相似问题