【发布时间】:2020-12-03 15:00:00
【问题描述】:
我需要在子组件中处理我父组件的状态。
考虑以下代码:
export default class App extends React.Component {
state = {
products: [
{
id: 1,
details: 'this is a macbook',
image: require('./Images/macbook.jpg'),
price: '1000$',
},
{
id: 2,
details: 'this is a PS4 pro',
image: require('./Images/ps4pro.jpeg'),
price: '500$',
},
{
id: 3,
details: 'this is a beats',
image: require('./Images/beats.jpeg'),
price: '200$',
},
]
}
showProds = () => {
let prods = [];
for (let i = 0; i <= this.state.products.length - 1; i++) {
prods.push(<Product key={this.state.products[i].id} id={this.state.products[i].id} details={this.state.products[i].details} img={this.state.products[i].image} />)
}
return prods;
}
delete = () => {
//handle deleting a product
}
render() {
return <ScrollView>
{this.showProds()}
</ScrollView>
}
}
如您所见,这是我的主要(父)组件,它的状态是一组示例产品,我通过它们循环显示在屏幕上,这是我的产品组件:
const Product = (props) => {
return (
<View style={styles.card}>
<View style={styles.prod}>
<Text style={styles.prod_details}>{props.details}</Text>
<Image style={styles.img} source={props.img} />
</View>
<View style={styles.btn}>
<TouchableOpacity onPress={() => this.Delete()}> //my handler is here
<Text style={styles.btn_text}>Delete</Text>
</TouchableOpacity>
</View>
</View >
)
}
我需要在 TouchableOpacity 元素中有我的处理程序(每个产品都有一个 TO 处理程序),以便我可以在删除函数中处理我的父状态。但是这种方式会导致undefined is not an object 错误。
我该如何处理?
【问题讨论】:
标签: android reactjs react-native