Reputation: 550
I try to access the key prop in TextInput to save it in the state (and then in Redux). I create in an array so many TextInput fields as I got from my first screen:
render() {
const { playerAmount } = this.props;
var textBoxes = [];
for (var i = 0; i < playerAmount; i++) {
var placeholderText = 'Player ' + (i + 1);
textBoxes.push(
<TextInput
key = {i+1}
onChangeText={(text) => {
const Player = Object.assign({}, this.state.Player, { playerName: text, playerNumber: this.props.key});
this.setState({ Player });
}}
placeholder={placeholderText}
placeholderTextColor="grey"
>
</TextInput>
);
Now I try to set the state of the playerNumber with the key prop. I tried it with key / {key} / this.props.key
Constructor:
constructor(props) {
super(props);
this.state =
{
Player:
{
playerName: "",
playerNumber: 0
}
}
}
As you can see I am pretty new to React-Native. Do you have any idea how to solve this?
Thank you so much! :)
Upvotes: 0
Views: 1991
Reputation: 471
class Firebase extends React.Component{
state={
name:'',
number:'',
}
onChangeTextInput = key => val => {
this.setState({[key]:val})
}
render(){
return(
<View>
<TextInput
value={this.state.name}
onChangeText={this.onChangeTextInput('name')}
/>
<TextInput
value={this.state.number}
onChangeText={this.onChangeTextInput('number')}
/>
</View>
)
}
}
Upvotes: 0
Reputation: 10961
Why not just do this?
render() {
const { playerAmount } = this.props;
var textBoxes = [];
for (var i = 0; i < playerAmount; i++) {
var placeholderText = 'Player ' + (i + 1);
const key = i+1;
textBoxes.push(
<TextInput
key = {key}
onChangeText={(text) => {
const Player = Object.assign({}, this.state.Player, { playerName: text, playerNumber: key});
this.setState({ Player });
}}
placeholder={placeholderText}
placeholderTextColor="grey"
>
</TextInput>
);
}
}
Upvotes: 1