admin管理员组文章数量:1279048
Description
From the sample code below, the FlatList returns n-number of TextInput, when a value is entered on a particular TextInput it keeps re-rendering every other TextInput.
Sample Code
<FlatList
...........
renderItem ={this.renderItem}
/>
renderItem=(item)=>{
<Text>{item.name}</Text>
<TextInput
.........
onChangeText ={(text)=>this.setState({text})}
value={this. state.text}
/>
}
Solution
I have tried to assign a key to the TextInput but don't know how to go about it
Description
From the sample code below, the FlatList returns n-number of TextInput, when a value is entered on a particular TextInput it keeps re-rendering every other TextInput.
Sample Code
<FlatList
...........
renderItem ={this.renderItem}
/>
renderItem=(item)=>{
<Text>{item.name}</Text>
<TextInput
.........
onChangeText ={(text)=>this.setState({text})}
value={this. state.text}
/>
}
Solution
I have tried to assign a key to the TextInput but don't know how to go about it
Share Improve this question edited Sep 12, 2023 at 17:25 Moplio asked Jul 6, 2018 at 8:47 MoplioMoplio 3502 gold badges5 silver badges16 bronze badges2 Answers
Reset to default 9Update: Added Complete Example
You need to maintain textinputs state as an array to store the values for each textinput
import React, { Component } from 'react';
import {
View,
Text,
FlatList,
TouchableOpacity,
TextInput,
} from 'react-native';
export class Demo extends Component {
state = {
textInputs: [],
};
render() {
return (
<View style={{ flex: 1, marginTop: 20 }}>
<FlatList
style={{ flex: 1 }}
data={[1, 2, 3, 4, 5]}
renderItem={({ item, index }) => {
return (
<View
style={{
height: 100,
backgroundColor: '#F0F0F0',
width: 300,
alignSelf: 'center',
margin: 10,
}}
>
<TextInput
style={{
flex: 1,
backgroundColor: '#C0C0C0',
}}
onChangeText={text => {
let { textInputs } = this.state;
textInputs[index] = text;
this.setState({
textInputs,
});
}}
value={this.state.textInputs[index]}
/>
<TouchableOpacity
style={{
backgroundColor: 'red',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}
onPress={() => {
let { textInputs } = this.state;
textInputs[index] = '';
this.setState({
textInputs,
});
}}
>
<Text> Clear</Text>
</TouchableOpacity>
</View>
);
}}
/>
</View>
);
}
}
Just remove value
attribute from your TextInput
, but this is not the solution as the value is stores into single state only, so if you want to get value of multiple textinputs you have to create rowrender and array of states
<TextInput
.........
onChangeText ={(text)=>this.setState({text})}
//value={this. state.text}
/>
本文标签: javascriptTextInput inside a FlatListStack Overflow
版权声明:本文标题:javascript - TextInput inside a FlatList - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741302204a2371154.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论