我正在创建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 类中创建这些函数 (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})
}
关于react-native - 映射 React Native 时更新输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48578127/