child
import React, {Component} from 'react'
class Card extends Component {
render() {
let props = this.props;
return(
<div className="card-main">
<img src={`http://image.tmdb.org/t/p/w342/${props.path}`} alt="Poster" />
<div className="card-deatils">
<h4 className="card-name">{props.name}</h4>
<h4 className="id card-name">{props.id}</h4>
</div>
</div>
);
}
}
export default Card;
我想获取存储在“id”类中的id。问题是,从之前的组件来看,页面中的金额卡至少有 20 张,而我理想的情况是将 id 传递回其父组件。我尝试过的大多数方法都给出未定义的值。
父级
import React, {Component} from 'react'
import Card from './Card'
class CardArray extends Component {
render() {
var props = this.props
return (
<div className="pop-movie-container">
<div className="card">
{
props.popNames.map((val,index) => {
return(
<Card
key ={props.popId[index]}
id={props.popId[index]}
name={props.popNames[index]}
path={props.popPath[index]}
/>
);
})
}
</div>
<div className="load-more">
<button className="btn btn-12" onClick={props.change}>LOAD MORE</button>
</div>
</div>
);
}
}
export default CardArray;
popNames 是一个至少包含 20 个名称的数组,单击“加载更多”时会增加 20 个名称。
所以,理想情况下我想要的是从传递给 CardArray 的 Card 获取 id。
因此,当有人点击卡片时,可以使用电影的 id 从 api 获取更多信息
最佳答案
父级
import React, { Component } from "react";
import Card from "./Card";
class CardArray extends Component {
fetchDetails = (id) => {
// fetching logic goes here
}
render() {
var props = this.props;
return (
<div className="pop-movie-container">
<div className="card">
{props.popNames.map((val, index) => {
return (
<Card
key={props.popId[index]}
id={props.popId[index]}
name={props.popNames[index]}
path={props.popPath[index]}
handelClick={this.fetchDetails}
/>
);
})}
</div>
<div className="load-more">
<button className="btn btn-12" onClick={props.change}>
LOAD MORE
</button>
</div>
</div>
);
}
}
export default CardArray;
child
import React, { Component } from "react";
class Card extends Component {
render() {
let props = this.props;
return (
<div className="card-main" onClick={() => this.props.handelClick(this.props.id)}>
<img
src={`http://image.tmdb.org/t/p/w342/${props.path}`}
alt="Poster"
/>
<div className="card-deatils">
<h4 className="card-name">{props.name}</h4>
<h4 className="id card-name">{props.id}</h4>
</div>
</div>
);
}
}
export default Card;
你可以将一个函数作为 props 传递给 child,而 child 可以使用 id 调用该函数。 如果您需要更多解释,请告诉我。
也可以直接通过一次快速建议
name={val}<
而不是 name={props.popNames[index]}
关于javascript - 在 React 中从 <h4> 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50817124/