简体   繁体   English

从映射数组React.js抓取对象

[英]Grabbing Object from mapped array React.js

I am trying to write a function that will save a specific object in an array that the user will click I am unsure of how to grab the data I need from the object 我正在尝试编写一个将特定对象保存在用户单击的数组中的函数,我不确定如何从该对象中获取所需的数据

this is the function at the moment: 这是目前的功能:

 saveArticle = event => { const userId = localStorage.getItem("userId") event.preventDefault(); const article = { title: this.title, summary: this.summary, link: this.link, image: this.image, userId: userId } console.log(article) // API.saveArticle() } 

and this is the component where I map through the array 这是我通过数组映射的组件

 const articleCard = props => { const { classes } = props return ( <div> {props.articles.map((article, i) => { console.log(article); return ( <div key={i}> <Card className={classes.card}> <CardActionArea> <CardMedia className={classes.media} image={article.image} title={article.title} href={article.link} /> <CardContent> <Typography gutterBottom variant="headline"> {article.title} </Typography> <Typography component="p"> {article.summary} </Typography> </CardContent> </CardActionArea> <CardActions> <Button href={article.link} size="small" color="primary"> Read Article </Button> <Button onClick={props.saveArticle} size="small" color="primary"> Favorite </Button> </CardActions> </Card> </div> ) })} </div> ) } 

I cant seem to grab the objects properties that I'd like to get and I am pretty lost as too how! 我似乎无法抓住我想要获得的对象属性,而且我也很迷失!

any help would be much appreciated thanks guys! 任何帮助将不胜感激谢谢大家!

Try this 尝试这个

<Button onClick={(e) => props.saveArticle(article, e)} size="small" color="primary">
    Favorite
</Button>

and

 saveArticle = (article, event) => {
    const userId = localStorage.getItem('userId');
    event.preventDefault();
    const article = {
      title: article.title,
      summary: article.summary,
      link: article.link,
      image: article.image,
      userId: userId
    };
    console.log(article);
    // API.saveArticle()
  };

Reference: Passing Arguments to Event Handlers 参考:将参数传递给事件处理程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM