目录
1.children
一个组件通过 props 除了能给获取自身属性上的值,还可以获取被组件包含的内容,也就是外部子组件,前面我们写的组件更多的是作为一个单标签组件,实际应用中很多组件是双标签的,也就是可以包含内容的,也可称为:容器组件,那么组件包含的内容,我们就可以通过 props.children 来获取。
1.1dialog 组件
需求:对话框标题和内容可变。如,警告,提示等。当对话框内容,使用表单或表格实现时比较复杂,直接加载表单或表格,页面结构会混乱冗杂。
通过props属性将标签,表单,列表等内容传递到子组件,子组件中需要使用到的地方通过this.props.children加载传递过来的内容即可。
1.1.1CSS
.dialog {
position: fixed;
left: 50%;
top: 30%;
transform: translateX(-50%) translateY(-50%) ;
border-radius: 2px;
box-shadow: 0 1px 3px rgba(0,0,0,.3);
box-sizing: border-box;
background: #fff;
width: 30%;
}
.dialog_header {
padding: 20px 20px 0;
text-align: left;
}
.dialog_title {
font-size: 16px;
font-weight: 700;
color: #1f2d3d;
}
.dialog_content {
padding: 30px 20px;
color: #48576a;
font-size: 14px;
text-align: left;
}
.dialog_close_btn {
position: absolute;
right: 10px;
top: 5px;
}
.dialog_close_btn:before {
content: 'x';
color: #999;
font-size: 20px;
cursor: pointer;
}
1.1.2 dialog.js
import React from 'react';
import '../css/dialog.css'
class Dialog extends React.Component {
static defaultProps = {
title: '这是默认标题'
}
render() {
return (
<div className="dialog">
<i className="dialog_close_btn"></i>
<div className="dialog_header">
<span className="dialog_title">{this.props.title}</span>
</div>
<div className="dialog_content">
{this.props.children}
</div>
</div>
);
}
}
export default Dialog;
1.1.3App.js
import React from 'react';
import './App.css';
import Dialog from './components/Dialog';
function App() {
return (
<div className="App">
<Dialog title={"警告"}>
{/* 整个form表单都是作为内容传递给子组件Dialog,子组件通过this.props.children可以得到整个form表单结构 */}
<form id="dialog_form" method="post">
用户名:<input type="text" name="name" />
</form>
</Dialog>
</div>
);
}
export default App;
效果: