[英]Pass, Receive, and Use function into child Component
我仍在学习ReactJS / React Native,我确信自己会遇到愚蠢的事情。 这是我的情况:我想在子组件中接收数据并将其显示在Modal中。 所以:
我有一个像这样的功能(axios,API等):
getProductInfo = (product_id) => {
axios.get(
`API-EXAMPLE`
)
.then((response) => {
this.setState({
isVisible: false,
productInfo: response.data
})
console.log(this.state.productInfo);
})
}
我通过“ onModalPress”将该函数传递给我的子组件:
<CatalogList productsList={this.state.displayProducts} onModalPress={this.getProductInfo}/>
在这里,有关子组件的一些信息:
const CatalogList = ({productsList, onModalPress}) => (
<Card containerStyle={styles.container}>
<View style={{ padding:20, margin:0, flexDirection: 'row', flexWrap: 'wrap', flex: 1, justifyContent: 'space-between' }}>
{
productsList.map((p, i) => {
return (
<TouchableHighlight key={i} onPress={() => onModalPress(p.id)}>
<View style={style.card}>
<View style={style.content}>
<View style={{width: 170, zIndex: 2}}>
<Text style={style.name}>{p.id}</Text>
<Text style={style.name}>{p.name}</Text>
<Text style={style.winemaker}>Domaine : {p.domain}</Text>
<Text style={style.winemaker}>Origine : {p.wine_origin}</Text>
<Text style={style.aop}>Appellation : {p.appellation}</Text>
</View>
<Image
style={style.image}
source={{ uri: p.image, width: 140, height: 225, }}
/>
</View>
<View style={style.entitled}>
<Text style={[style.priceText, style.cadetGrey]}>{p.publicPriceText}</Text>
<Text style={style.priceText}>{p.subscriberPriceText}</Text>
</View>
<View style={style.row}>
<Text style={[style.price, style.cadetGrey]}>{p.price} €</Text>
<Text style={style.price}>{p.subscriber_price} €</Text>
</View>
<View style={[{backgroundColor: p.label_colour}, style.label]}>
<Text style={style.labelText}>{p.label}</Text>
</View>
<Modal isVisible={false}>
<View style={{ flex: 1 }}>
{/* <Text>{productInfo.rewiew_wine_waiter}</Text> */}
</View>
</Modal>
</View>
</TouchableHighlight>
);
})
}
</View>
</Card>
);
“ p.id”来自我通过另一个Axios API调用获得的另一个数据(productList)。 通过“ p.id”,我获得了我的函数中需要的product_id
getProductInfo
一切正常,我在console.log(this.state.productInfo)中显示信息。
我的问题,我认为这很容易...这就是我如何“存储/存储” console.log中的此信息,并在const / props中在我的Modal中使用它,并在此示例中进行调用:
<Modal isVisible={false}>
<View style={{ flex: 1 }}>
<Text>{productInfo.rewiew_wine_waiter}</Text>
</View>
</Modal>
当然,任何其他建议都欢迎!
React只是关于组件层次结构中的单向数据流
假设您有一个Container
组件来获取所有数据:
class MyContainer extends Component{
state = {
myItensToDisplay: []
}
componentDidMount(){
//axios request
.then(res => this.setState({myItensToDisplay: res.itens}))
}
}
看起来不错! 现在,您已经获取了要显示的所有数据,并以容器的状态存储了它们。 让我们将其传递给Item
组件:
class MyContainer extends Component{
// All the code from above
render(){
const itens = this.state.myDataToDisplay.map( item =>{
return(<Item name={item.name} price={item.price} />);
})
return(
<div>
{itens}
</div>
)
}
}
现在,您要获取要在父组件中显示的所有数据,然后通过prop将该数据分配给它的子组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.