props.order.main等是来自另一个组件的数据。在仍在使用道具时,是否可以将行函数变成类组件?
const Row = (props)=> {
var sub_items = [];
const number_items = props.order.num_sub_items;
for(let i = 0; i < number_items; i++){
sub_items.push(
<View key = {i} style={{flexDirection: 'row', flex:1, justifyContent:'space-between' }}>
<Text style={styles.text}>{`${props.order.sub_item_name[i]}`}</Text>
<Text style={styles.text}>{`${props.order.sub_item_value[i]}`}</Text>
</View>
)
}
return (
<View onPress={ () => {console.log("Row pressed")}}>
<View style={styles.container}>
<Text style={styles.text}>{`${props.order.main}`}</Text>
{sub_items}
</View>
<ActionButton onPress={this._addItem.bind(this)} title="Accept Order" />
</View>
)
}
和Row在这里被称为:
render() {
return (
<View style={styles.container}>
<ListView
style={styles.container}
dataSource={this.state.dataSource}
renderRow={(data, onPress) => <Row {...data} />}
renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
renderSectionHeader={(sectionData) => <SectionHeader {...sectionData} />}
/>
<ActionButton onPress={this._addItem.bind(this)} title="Accept Oldest Order" />
</View>
);
}
谢谢!
应该非常简单,只需将代码移动到render()
中,然后使用this.props
而不是props
:
class Row extends Component {
render() {
var sub_items = [], props = this.props;
const number_items = props.order.num_sub_items;
for(let i = 0; i < number_items; i++){
sub_items.push(
<View key = {i} style={{flexDirection: 'row', flex:1, justifyContent:'space-between' }}>
<Text style={styles.text}>{`${props.order.sub_item_name[i]}`}</Text>
<Text style={styles.text}>{`${props.order.sub_item_value[i]}`}</Text>
</View>
)
}
return (
<View onPress={ () => {console.log("Row pressed")}}>
<View style={styles.container}>
<Text style={styles.text}>{`${props.order.main}`}</Text>
{sub_items}
</View>
<ActionButton onPress={this._addItem.bind(this)} title="Accept Order" />
</View>
)
}
}
当然 - 这是反应中的自然模式,很容易实现。最大的区别是使用this.props
引用了props
,因为从父级授予props
绑定到组件上下文。尝试以下操作:
class Row extends React.Component {
render() {
const sub_items = [];
const number_items = this.props.order.num_sub_items;
for (let i = 0; i < number_items; i++) {
sub_items.push(
<View key = {i} style={{flexDirection: 'row', flex:1, justifyContent:'space-between' }}>
<Text style={styles.text}>{`${this.props.order.sub_item_name[i]}`}</Text>
<Text style={styles.text}>{`${this.props.order.sub_item_value[i]}`}</Text>
</View>
)
}
return (
<View onPress={ () => {console.log("Row pressed")}}>
<View style={styles.container}>
<Text style={styles.text}>{`${props.order.main}`}</Text>
{sub_items}
</View>
<ActionButton onPress={this._addItem.bind(this)} title="Accept Order" />
</View>
);
}
}