React之自定义Model

王大爷 2019年09月28日 410次浏览

自定义模态框组件

使用场景,点击按钮展示模态框组件,模态框组件包含内容:
1.模态框标题 name
2.模态框内容 text
3.取消事件Action: closeAction , 确认事件Action: commitAction
4.show 用来判断是否展示

先写父组件部分,这里要导入模态框组件,还要写个button,通过button触发事件,控制模态框的展示。

app.jsx 父组件调用模态框组件:

import React from "react";
import Model from "../componets/Model.jsx";
export default class App extends React.Componet{
	state = {
	  show:false
	}
	open=()=> {
		this.setState({show:true});	
	}

  closeAlert = () => {
    //取消Action
    this.setState({
      show: false
    });
  };
  commitAction = () => {
    //确认Action
    this.setState({
      show: false
    });
  };
	render(){
		return(
			 <button onClick={this.open.bind(this)}>开启宝藏</button>
			 <Model  show={this.state.show} 
							name="模态框标题"
							text="模态框内容"
							closeAction={ this.closeAction.bind(this)}
							commitAction={this.commitAction.bind(this)}
			 />
		)
	}
}

Model.jsx

import React from "react";
export default class Model extends React.Component {
   //数据类型验证
	static propTypes = {
	    name: PropTypes.string,
	    text: PropTypes.string,
	    closeAlert: PropTypes.func,
	    commitAction: PropTypes.func,
	    show: PropTypes.bool
	  };
	  //state 状态初始化
	constructor(props){
		super(props);
		this.state = {
			show: false,
			name:" ",
			text:" "
		}
	}
	confirm = ()=>{
		this.props.commitAction ()
	}
	cancel = () => {
		this.props.closeAction();
	}
render(){
	return (
		<div  className="alert_moudel"
	          style={this.props.show ? { display: "block" } : { display: "none" }}>
	        <h1 className="alert_title">{this.props.name}</h1>
	        <p className="alert_content">{this.props.text}</p>
	        <div className="button_group">
	          <button onClick={this.cancel.bind(this)}>取消</button>
	          <button onClick={this.confirm.bind(this)}  className="alert_confirm">
	            确定
	          </button>
	        </div>
        </div>
	)
}
}

在这里插入图片描述

总结: 父组件向子组件的数据传递通过 props, 子组件向父组件传递数据使用props.callbck