Loop in react
I want to make a list of fields depending on the number of the player that user has selected. I wanted to make something like this:
generatePaymentField() {
var noGuest = this.state.guest;
var payment =
<View>
<View>
<View><Text>No</Text></View>
<View><Text>Name</Text></View>
<View><Text>Preference</Text></View>
</View>;
for (var i=0; i < noGuest; i++) {
payment = payment +
<View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
</View>;
}
return payment;
}
render () {
var payment = this.generatePaymentField();
this.setState({payment : payment});
return (
<View>
{this.state.payment}
</View>;
)
}
But react-native regarded the syntax above as 'unexpected token' pointing at the for loop line. Is there any other way I can achieve doing this?
这应该工作
render(){
var payments = [];
for(let i = 0; i < noGuest; i++){
payments.push(
<View key = {i}>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
</View>
)
}
return (
<View>
<View>
<View><Text>No</Text></View>
<View><Text>Name</Text></View>
<View><Text>Preference</Text></View>
</View>
{ payments }
</View>
)
}
First of all, I recommend writing the item you want to render multiple times (in your case list of fields) as a separate component:
function Field() {
return (
<View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
<View>
<TextInput />
</View>
</View>
);
}
Then, in your case, when rendering based on some number and not a list, I'd move the for loop outside of the render method for a more readable code:
renderFields() {
const noGuest = this.state.guest;
const fields = [];
for (let i=0; i < noGuest; i++) {
// Try avoiding the use of index as a key, it has to be unique!
fields.push(
<Field key={"guest_"+i} />
);
}
return fields;
}
render () {
return (
<View>
<View>
<View><Text>No</Text></View>
<View><Text>Name</Text></View>
<View><Text>Preference</Text></View>
</View>
{this.renderFields()}
</View>;
)
}
However, there are many more ways to render looped content in react native. Most of the ways are covered in this article, so please check it out if you're interested in more details! The examples in article are from React, but everything applies to React Native as well!
链接地址: http://www.djcxy.com/p/52050.html上一篇: 如何在React中呈现HTML评论?
下一篇: 循环反应