首页 > 解决方案 > 如何使用 onClick 事件在 React 中查找子元素

问题描述

我正在触发 Click 事件,如下所示,我想访问子元素“.details”。请建议如何实现,我想在单击父 .movi​​e 时将颜色应用于子节点 '.details'

return (
  <div className="movie" onClick={e => this.selectMovie(e)}>
    <div className="floatleft">
      <img alt={Title} src={Poster} />
    </div>
    <div className="floaright">
      <h3>{Title}</h3>
      Year : <b>{Year}</b>
      <br />
      <br />
      Director : <b>{Director}</b>
      <br />
      Production : <b>{Production}</b>
      <br />
      <br />
      Actor : <b>{Actors}</b>
      <br />
      <br />
      Released : <b>{Released}</b>
      <br />
    </div>
    <div className="details">
      =============
      {Runtime}
      {imdbRating}
    </div>
  </div>
);

selectMovie = e => {
  console.log(e);
  //console.log(data)
  //event.currentTarget.find('.details').style.backgroundColor = '#ccc';
};

标签: reactjs

解决方案


不推荐,您可以使用状态,并在此基础上添加类或动态样式。

class MyComponent extends React.Component {
  state = {
    isSelected: false
  };
  render() {
    return (
      <div className="movie" onClick={e => this.selectMovie(e)}>
        <div className="floatleft">
          <img alt={Title} src={Poster} />
        </div>
        <div className="floaright">
          <h3>{Title}</h3>
          Year : <b>{Year}</b>
          <br />
          <br />
          Director : <b>{Director}</b>
          <br />
          Production : <b>{Production}</b>
          <br />
          <br />
          Actor : <b>{Actors}</b>
          <br />
          <br />
          Released : <b>{Released}</b>
          <br />
        </div>
        <div className="details" style={isSelected ? { backgroundColor: '#ccc'} : {}}>
          =============
          {Runtime}
          {imdbRating}
        </div>
      </div>
    );
  }

  selectMovie = e => {
    console.log(e);
    this.setState({ isSelected: true });
  };
}

良好的做法也是使它成为一个<button></button>元素而不是一个 div。如果您有其他功能,例如单击此按钮时提交内容,请使用<form></form>

  <button className="movie" onClick={e => this.selectMovie(e)}>
    <div className="floatleft">
      <img alt={Title} src={Poster} />
    </div>
    <div className="floaright">
      <h3>{Title}</h3>
      Year : <b>{Year}</b>
      <br />
      <br />
      Director : <b>{Director}</b>
      <br />
      Production : <b>{Production}</b>
      <br />
      <br />
      Actor : <b>{Actors}</b>
      <br />
      <br />
      Released : <b>{Released}</b>
      <br />
    </div>
    <div className="details" style={isSelected ? { backgroundColor: '#ccc'} : {}}>
      =============
      {Runtime}
      {imdbRating}
    </div>
  </button>

推荐阅读