有一个问题,e.target.value在React中返回Undefined

时间:2016-11-05 14:25:36

标签: reactjs onclick target e

我有一个功能,您可以单击一个img并查看可点击的名称列表....当您单击一个名称时,该人物图像应取代原始图像。我和一个艺术家api合作,而不是我在控制台中出错,图像变成了一个艺术家的img,其名字是“未定义的”......奇怪的。可能不是一个巨大的修复,但我已经被这个问题折磨了一段时间了。

searchForArtist(query) {
    request.get(`https://api.spotify.com/v1/search?q=${query}&type=artist`)
      .then((response) => {
        const artist = response.body.artists.items[0];
        const name = artist.name;
        const id = artist.id;
        const img_url = artist.images[0].url;
        this.setState({
          selectedArtist: {
            name,
            id,
            img_url,
          },
        });
      })
      .then(() => {
        this.getArtistAlbums();
      })
      .catch((err) => {
        console.error(err);
      });
  }

  getSubsequentCollabs(artist) {
    this.setState({
      selectedArtist: {},
      selectedAlbums: {},
      artistCounts: {},
    });
    console.log(artist);
    this.searchForArtist(artist);
  }

  artistOnClick(e) {
    console.log(e);
    let artist = e.target.value;
    this.getSubsequentCollabs(artist);
  }

我有另一个组件这样做:

const Artist = ({name, artistOnClick}) => {
  return (
    <div name={name} onClick={artistOnClick}>
      {name}
    </div>
  )
}

export default Artist;

4 个答案:

答案 0 :(得分:2)

event.target会为您提供目标HTML元素。 Javascript会将Node的所有属性作为event.target的属性。

例如:

<div id="hello">Hello</div>

e.target.id //returns 'hello'

有一些特殊情况,例如inputs隐含属性value。但是,对于其他HTML元素,您需要明确指定属性。

所以,HTML应该是这样的

const Artist = ({name, artistOnClick}) => {
  return (
    <div value={name} onClick={artistOnClick}>
      {name}
    </div>
  )
}

e.target.value //return the name

OR

const Artist = ({name, artistOnClick}) => {
  return (
    <div onClick={() => artistOnClick(name)}>
      {name}
    </div>
  )
}

e.target.name //returns the name 

希望这有帮助!

答案 1 :(得分:1)

div元素没有值属性,因此在该特定click事件的事件对象的背面不能传递任何内容。

根据您的预期,您可以通过以下方式解决问题:

const Artist = ({name, artistOnClick}) => {
  return (
    <div onClick={() => artistOnClick(name)}>
      {name}
    </div>
  )
}

export default Artist;

答案 2 :(得分:0)

我遇到了类似的问题,我的输入字段返回了e.target.value的未定义

我解决了

onChange={this.mymethod.bind(this)}

我希望它能帮助其他人。

答案 3 :(得分:0)

在React中,如果e.target.value没有保存在另一个变量中,它将显示为空。 例如:

const onChange = e => {
    console.log(e.target.value);
    setState(
        blah: e.target.value
    )
}

在上面的示例中,console.log(e.target.value)将显示为值,但是在setState中,e.target.value将是未定义的。

您需要将e.target.value保存在新变量中,才能使用它。

const eTarget = e.target.value;

React使用事件池。 Read about it here:

从文档中

Note:

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.
相关问题