jquery - React - jQuery - 在文档加载时添加 onClick 监听器
问题描述
我需要在文档加载时添加一个 onClick 侦听器。由于几个原因,我不想使用 state 来做到这一点。首先,我想创建一个可以在任何地方使用并始终显示下一个元素的规则。其次,我还想添加淡入淡出或幻灯片效果。下面的代码不起作用。
componentDidMount() {
$(document).ready(function() {
$(".showNext").click(function() {
$(this).next().slideToggle();
});
});
}
if (!loadingData)
render() {
return(
<div>
<div className="showNext">Show element #1</div>
<div style={{display:"none"}}>Element #1</div>
<div className="showNext">Show element #2</div>
<div style={{display:"none"}}>Element #2</div>
</div>
);
}
} else {
<div>Loading ... </div>
}
解决方案
如果您已经在使用该componentDidMount
方法,那么您似乎并不关心创建任何函数,请使用以下代码更新您的代码:
handleClickMethod = () => console.log('clicked')
render() {
return(
<div>
<div className="showNext">Show element #1</div>
<div style={{display:"none"}} onClick={this.handleClickMethod}>Element #1</div>
<div className="showNext">Show element #2</div>
<div style={{display:"none"}} onClick={this.handleClickMethod}>Element #2</div>
</div>
);
}
甚至更好!创建一个可点击的组件!
class Clickable extends Component {
_handleClick = () => {
console.log('clicked')
this.props.onClick && this.props.onClick()
}
render() {
const {...props} = this.props
return <div {...props} onClick={this._handleClick}/>
}
}
并在您的主要组件中像这样使用它:
render() {
return(
<div>
<Clickable className="showNext">Show element #1</Clickable>
<div style={{display:"none"}}>Element #1</div>
<Clickable className="showNext">Show element #2</Clickable>
<div style={{display:"none"}}>Element #2</div>
</div>
);
}
无论如何,对于你想要完成的事情,你会更好地使用更像这样的东西:
class Toggleable extends Component {
state = {toggled: false}
_toggleDiv = () => {
this.setState({toggled: !this.state.toggled})
}
render() {
return (
<div>
<div className="showNext" onClick={this._toggleDiv}>{this.props.showText}</div>
{this.state.toggled && <div>{this.props.text}</div>}
</div>
)
}
}
并在您的主要组件中像这样使用它:
render() {
return(
<div>
<Toggleable showText={'Show element #1'} text={'Element #1'}/>
<Toggleable showText={'Show element #2'} text={'Element #2'}/>
</div>
);
}
欢迎来到模块化编程!
推荐阅读
- node.js - Node.js:如何从一个字符串和另一个数组创建一个数组?
- php - 生成具有给定约束的给定数量的随机数(PHP)?
- android - Flutter:将图形叠加在 Firebase 视觉检测到的条形码上
- asp.net-core - .net 核心上的 Servicestack 执行超时
- apache-kafka - Kafka Connect JDBC Sink 可以转储原始数据吗?
- python - 如果出现禁止字符,如何捕捉 wx.stc.StyledTextEvent 中的文本更改并更新显示
- reactjs - React 17.0.1 - 使用动态路径导入组件
- python - 以下代码会断开所有传入或传出的 PyQt 信号吗?
- flutter - Flutter Socket-Io 没有连接到服务器?
- haskell - 范畴论基础