ReactJS onClick事件到另一个组件

时间:2018-04-19 21:47:29

标签: javascript reactjs

如何在锚点上使用onClick来设置另一个组件中的setState?

Card.js onClick

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

1 个答案:

答案 0 :(得分:0)

你可以

  • 将您的卡组件转换为某个类,并将其命名为hasOpenLightBox
  • hasOpenLightBox
  • 中将true设为this.openLightbox
  • 将PropertyLightbox作为道具:<PropertyLightbox isOpen={this.state.hasOpenLightBox}
  • setState或根据isOpen道具
  • 在PropertyLightbox内做任何你需要做的事情