动态组件:通过引用调用元素

时间:2018-02-23 09:53:16

标签: javascript reactjs ref

我的应用程序的一部分是图库。当用户点击图像时,我想在图像上放置一个不透明图层,以显示它已被选中。

当我显示图层时,我点击图像取消选择它,我自然会点击图层。 这是相关的ReactJS代码,用于显示我的意思:

{images.map((i, idx) => ( 
    <div key={"cont"+idx} className="container">
        <img src={i.images} ref={"img"+idx} />
        <div onClick={this.handleIconDeselect} id={"div_"+idx}></div>
    </div>  
    )
)}

我试图给img一个唯一的引用(如上所示),但是我在选择正确的img时遇到了麻烦。

这就是我尝试选择正确图像的方式:

handleIconDeselect = (event) => {
  var imgref = "icon"+event.target.id.split("_").pop();
  this.refs.imgref.click();
}

但是,我收到以下错误消息:

TypeError: Cannot read property 'click' of undefined

如何在使用唯一参考时选择正确的图像?

或者,如果我试图实现这一点的方式是不好的做法(我知道你应该只在必要时使用refs),有什么更好的方法呢?

1 个答案:

答案 0 :(得分:0)

尝试使用状态:https://codesandbox.io/s/m4276x643y 也许这不是最好的方式,但它给你一个粗略的想法。

import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";

const coverStyle = {
  position: "fixed",
  top: 0,
  left: 0,
  zIndex: -1,
  opacity: 0,
  width: "100%",
  height: "100%",
  background: "#000"
};

const coverStyleShow = {
  ...coverStyle,
  zIndex: 1,
  opacity: 1
};

const imgShow = {
  zIndex: 10,
  position: "relative"
};

const images = [
  "https://dummyimage.com/100.png/f10/fff",
  "https://dummyimage.com/100.png/f20/fff",
  "https://dummyimage.com/100.png/f30/fff",
  "https://dummyimage.com/100.png/f40/fff",
  "https://dummyimage.com/100.png/f50/fff",
  "https://dummyimage.com/100.png/f60/fff",
  "https://dummyimage.com/100.png/f70/fff"
];

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      cover: coverStyle,
      img: imgShow,
      imgId: null,
      imgShow: false
    };
  }
  handleImageClick = (target, idx) => {
    // you can do something with this "target"...

    this.setState({
      cover: coverStyle,
      coverShow: coverStyleShow,
      imgId: idx,
      imgShow: !this.state.imgShow
    });
  };
  render() {
    return (
      <div>
        <Hello name="CodeSandbox" />
        <h2>Start editing to see some magic happen {"\u2728"}</h2>
        <div>
          {images.map((img, idx) => (
            <img
              key={img}
              src={img}
              style={idx === this.state.imgId ? this.state.img : null}
              onClick={event => this.handleImageClick(event.target, idx)}
              alt="dummy img"
            />
          ))}
        </div>
        <span
          style={this.state.imgShow ? this.state.coverShow : this.state.cover}
        />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));