繁体   English   中英

单击子组件获取父组件属性

[英]Get parent component properties on click of child component

我不确定这是否是解决问题的正确方法,所以我也对其他方法持开放态度。

当我单击子组件(图像)时,我希望能够访问父组件的属性。 到目前为止,这是我的代码:

父组件

import {Image, Grid, Row, Col} from 'react-bootstrap';
import React, { Component } from 'react';
import localForage from 'localforage';
import Activity from './activity';


testClick(e){
    console.log("click handled", e.target.getAttribute('value'));
}

render() {
    return (
        <Grid>
            <Row>
                <Col sm={4} smPush={4}>
                    <h2 className="center-header">Explore Ibiza</h2>
                </Col>
            </Row>
            <Row />
                <Activity handleClick={(e)=>{this.testClick(e)}} description="Dining" imageSource="https://lonelyplanetimages.imgix.net/mastheads/95971965.jpg?sharp=10&vib=20&w=1200" />
                <Activity description="Diving" imageSource="https://media-cdn.tripadvisor.com/media/photo-s/06/8d/1f/6a/linda-playa.jpg"/>
                <Activity onClick={this.handleClick} description="Boating" imageSource="https://lvs.luxury/wp-content/uploads/2015/06/1.jpg"/>
            <Row />
        </Grid>
    )
}

子组件

  return(
<Col sm={4}>
  <p>{props.description}</p>
  <Image onClick={props.handleClick} value={props.description}  src={props.imageSource}className="activity-image margin-bottom-5"/>
</Col>

说明

我现在能够获得值,但是如果我想获得父元素的description属性呢?

我不确定我是否理解正确但我认为你只需要将一个额外的参数传递给父的回调/处理程序。

也许这样的事情可能有所帮助:

<Image onClick={e => this.props.handleClick(e, props.description)} ...

暂无
暂无

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

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