我正在创建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})
}发布于 2018-02-02 18:15:47
您的输入值被设置为this.state.qty[Index]['qty']。要在文本编辑中更改它,您可以这样做。您不需要绑定函数,而是使用箭头函数,如下所示。
onChangeText={ (newValue) => {
this.setState({ <your-input-value-state>:newValue })
}}发布于 2018-02-02 19:17:57
您必须在onChange事件上分别更新每个Input的值。
将您的替换为以下Input
<Input value={this.state.qty[Index]['qty']}
onChange={this.handleChangeInput.bind(this, Index)}
style={{width:40,height:40,textAlign:'left'}}
/>并在调用event时使用Index相应地更新状态
handleChangeInput(index, value){
let {qty} = this.state;
let qty_update = qty.slice();
qty_update[index]['qty'] = value;
this.setState({qty: qty_update});
}https://stackoverflow.com/questions/48578127
复制相似问题