繁体   English   中英

ReactJS onClick事件到另一个组件

[英]ReactJS onClick event to another component

如何在锚点上使用onClick在另一个组件内设置状态?

带有onClick Card.js

import React from 'react'
import PropertyLightbox from '../global/PropertyLightbox'

const Card = (props) => {
    const propertyImages = props.gallery
    return (
        <Property id={props.slug}>
          <a onClick={this.openLightbox} href="javascript:;">Click to open lightbox</a>
          <PropertyLightbox lbImages={propertyImages}/>
        </Property>
    )
}
export default Card

PropertyLightbox.js setState openLightbox

class propertyLightbox extends React.Component {
    constructor() {
        super();
        this.state = { currentImage: 0 };
        this.openLightbox = this.openLightbox.bind(this);
    }

    openLightbox(event, obj) {
        this.setState({
            currentImage: obj.index,
            lightboxIsOpen: true,
        });
    }
    render() {
      return (
            <Lightbox images={this.props.propertyImages}
            isOpen={this.state.lightboxIsOpen}
            </Lightbox>
      )
    }
}

propertyLightbox.propTypes = {
    propertyImages: PropTypes.func,
}

export default propertyLightbox

你可以

  • 将您的Card组件转换为类并为其提供状态: hasOpenLightBox
  • 设置hasOpenLightBoxtruethis.openLightbox
  • 提供PropertyLightbox作为道具: <PropertyLightbox isOpen={this.state.hasOpenLightBox}
  • setState或在基于isOpen PropertyLightbox中执行所需的任何操作

暂无
暂无

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

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