React实现pc端的弹出框效果

2022-08-25 16:11:49

本文实例为大家分享了React实现pc端弹出框效果的具体代码,供大家参考,具体内容如下最近学习react碰见了一个小坑不知道为什么我在做一个弹出框的小demo很简单的一个小demo就是桌面上一个...

本文实例为大家分享了React实现pc端弹出框效果的具体代码,供大家参考,具体内容如下

最近学习react碰见了一个小坑 不知道为什么 我在做一个弹出框的小demo

React实现pc端的弹出框效果

很简单的一个小demo 就是桌面上一个按钮点击 出现一个弹出框 弹出框下面有一个遮罩层

1.我们现在src文件夹 下建立一个 Dialog 组件

import React,{Component} from 'react'
import '../dialog.css'
export default class Dialog extends Component {
  coandroidnstructor(props){
   super(props);
   this.state={}
  }
  render(){
    return (
      <div className="mask" style={{display:this.props.display}}>
        <div className="content">
          <button onClick={this.props.hide}>&times;</button>
        </div>
      </div>
    );
  }
}

2.然后就是css样式

.mask{
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  right: 0;
  background-color: #000;
  opacity: 0.4;
  color:#f00;
}
.content{
  position: fixed;
  height: 300px;
  width: 300px;
  left: 50%;
  top:50%;
  background-color: #fff;
  transform: translate(-50%,-50%);
}

3.再然后就是index.js的入口文件

import React,{Component } from 'react'
import ReactDOM from 'react-dom'
import Dialog from './components/Dailog';
import './index.css'
class Parent extends Component {
  constructor(props){
    super(props);
    this.state={display:'block'};
    this.tan=this.tan.bind(this);
    this.hide=this.hide.bind(this);
  }

  tan(){
    console.log(this);
    this.setState({display:'block'})
  }

  hide(){
    this.setState({display:'none'})
  }

  render(){
    return (
      <div>
       // 就是这里 不知道为什么我一把组件放到按钮下面 遮罩层 就不会覆盖掉按钮 很奇怪
        <Dialog display={this.state.display} hide={this.hide} />
        <button http://www.cppcns.comonClick={this.tan}>弹出</button>
      </div>
    );
  }
}
ReactDOM.render(<div><Parent /></div>,document.getElementById('root'))

在react中 子类调用父类的方法 是父类在子组件上面 绑定 方法然后在子组件中调用

<Dialog display={this.state.display} hide={this.hide} /> // android父类 通过props传递过去
<button onClick={this.props.hide}>&times;</button>  // 子类调用

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。