react判断点击位置是否为组件内,实现点击外部触发组件内事件(点击元素外隐藏元素)

本文介绍了如何在React中判断点击位置是否在组件内部,以此实现点击组件外部时触发组件内的事件,通常用于隐藏显示的元素。通过结合相关教程,探讨了如何适应新版React的要求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们拿到这样一个没做过的肯定是先一手百度
https://www.cnblogs.com/ives/p/11291769.html
结合所有的我发现这种还是不太符合新版要求

	export default class Relate extends Component {
    constructor(props) {
        super(props);
        this.refTest = React.createRef();
        this.state = {
            showurl:false,
        };
    }
	componentDidMount() {
        document.addEventListener('mousedown', (e)=>this.handleClickOutside(e), false);
    }
    componentWillUnmount() {
        document.removeEventListener('mousedown', (e)=>this.handleClickOutside(e), false);
    }
    handleClickOutside(e) {
        const target = e.target;
        console.log(target);
        console.log(this.refTest.current);
        if(this.refTest.current){
        // 组件已挂载且事件触发对象不在div内
            let result=findDOMNode(this.refTest.current).contains(e.target);
            if( !result) {
                console.log("ssscs");
                this.setState({
                    showurl:false
                });
            }  
        }
    }
    changeshow(){
        this.setState({
            showurl:!this.state.showurl
        })
    }
    render(){
	    return(
				<div className="relatedVideo" ref={this.refTest} style={{display:this.state.showurl?'':"none"}}>
                    {console.log(this.state.videos)}
                    <div className="relatedVideoTop" >
                        <div className="title">相关视频</div>
                        <div className="close" onClick={()=>this.changeshow()}></div>//自己css写的close按钮可自行删除
                    </div>
                    {this.state.videos.topics?this.show():''}
                </div>
		})
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值