reactjs - 如何使用 onClick 事件在 React 中查找子元素
问题描述
我正在触发 Click 事件,如下所示,我想访问子元素“.details”。请建议如何实现,我想在单击父 .movie 时将颜色应用于子节点 '.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';
};
解决方案
不推荐,您可以使用状态,并在此基础上添加类或动态样式。
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>
推荐阅读
- python - pandas apply typeError: 'float' object is not subscriptable, 在 pandas 的特定列上应用自定义函数
- reactjs - 如何(正确)使用 Typescript 输入表单(并且没有外部库)
- javascript - 返回带有“。”的对象 符号与括号
- gcc - Makefile 中意外处理的变量
- c - 从控制台读取 gotoxy() 点上的字符?
- azure-language-understanding - Turkish prepositions in LUIS
- aws-dms - 为什么 AWS DMS 任务验证成功记录数显示为 0?
- bash - Bash/AWS CLI:试图弄清楚如何在通过 AWS SSM 重启 EC2 实例组时通过 2 次检查来验证一系列正常运行时间
- javascript - 在富文本编辑器中使用 javascript 将 markdown 转换为 html
- reactjs - 这个路由器如何在 React.js 中工作 - 我不能像我想要的那样做链接