Вы можете сделать это с .map
, однако вы должны правильно настроить его так, чтобы каждый TextInput
имел свое собственное значение в состоянии.В настоящее время вы устанавливаете одно и то же значение в состоянии для каждого TextInput
, в результате каждый TextInput
имеет одно и то же значение.Понятно не то, что вы хотите.
- Создать начальный массив в состоянии (
textArray
), в котором все значения представлены в виде пустых строк, это будет использоваться для хранения значений из каждого TextInput
. - Установить для
focusedIndex
значение null в состоянии - Создать функцию, которая использует предыдущее значение состояния для обновления текущего состояния.
- Создайте функцию, которая будет обрабатывать изменение цвета поля, она будет просто сравнивать индекс
TextInput
с текущим focusedIndex
- Перебирать
textArray
и создавать TextInput
компоненты.Убедитесь, что каждый TextInput
имеет свое собственное значение в состоянии. - Убедитесь, что мы установили значение focusIndex в
onFocus
и onBlur
в TextInput
.Когда оно размыто, мы должны установить значение на ноль, чтобы оно убирало цвет границы при отклонении клавиатуры.
Так что мы могли бы сделать что-то вроде следующего
export default class App extends React.Component {
constructor(props) {
super(props);
// construct an array with the number of textInputs we require,
// each value an empty string
// set this array in state
// set the focusedIndex to null
let textArray = Array(6).fill('');
this.state = {
textArray: textArray,
focusedIndex: null
}
}
// this function will handle setting of the state when each TextInput changes
onChangeText = (text, index) => {
// as there are going to be a lot of setState calls
// we need access the prevState before we set the next state.
this.setState(prevState => {
prevState.textArray[index] = text
return {
textArray: prevState.textArray
}
}, () => console.log(this.state.textArray))
}
// handle the border color
handleBorderColor = (index) => {
return index === this.state.focusedIndex ? 'red' : 'grey'
}
render() {
// here we map the items in the `this.state.textArray`
// notice that each TextInput is give a specific value in state
// that will stop the overlap
return (
<View style={styles.container}>
{this.state.textArray.map((text, index) => {
return <TextInput
style={{height: 40, marginVertical: 10, borderColor: this.handleBorderColor(index), borderWidth: 1}}
onChangeText={text => this.onChangeText(text, index)}
value={this.state.textArray[index]}
placeholder={`placeholder for ${index}`}
onFocus={() => this.setState({focusedIndex: index})}
onBlur={() => this.setState({focusedIndex: null})}
/>
})}
</View>
);
}
}
Еслизатем вы хотите получить доступ к определенному значению для TextInput
, вы можете сделать это следующим образом
let value = this.state.textArray[index]; // where the index is the value you want
Вот пример закуски, показывающий работающий код https://snack.expo.io/@andypandy/map-multiple-textinputs
Это определенно стоитглядя на следующие статьи о состоянии, так как я использовал эти свойства в этом примере.
https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0 https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296 https://medium.learnreact.com/setstate-takes-a-function-56eb940f84b6