傳遞元素內(nèi)容
內(nèi)置組件:div、h1撒遣、p
<div>
asdfafasfafasdfasdf
</div>
如果給自定義組件傳遞元素內(nèi)容邮偎,則React會(huì)將元素內(nèi)容作為children屬性傳遞過去。
練習(xí)
demo1:圣杯布局
ThreeLayout組件
import React from 'react';
import './index.css'
export default function ThreeLayout(props) {
const defaultProps={
leftWidth:200,
rightWidth:200,
minWidth:800,
gap:0
}
const datas=Object.assign({},defaultProps,props)
return (
<div className='threelayout' style={{minWidth:datas.minWidth,height:300}}>
<div className='main'>{props.children}</div>
<div className='left-side' style={{minWidth:datas.leftWidth,marginRight:datas.gap}}>{props.left}</div>
<div className='right-side' style={{minWidth:datas.rightWidth,marginLeft:datas.gap}}>{props.right}</div>
</div>
)
}
index.css樣式文件
.threelayout{
display:flex;
}
.threelayout .main{
flex:1 1 auto;
order:2;
border:1px solid #e60000
}
.threelayout .left-side{
order:1;
background:lightblue
}
.threelayout .right-side{
order:3;
background:yellowgreen
}
在入口文件中使用
import React from "react";
import ReactDOM from 'react-dom';
import ThreeLayout from "./components/ThreeLayout";
const container=document.getElementById('root');
ReactDOM.render(
<ThreeLayout
left={<div>左側(cè)區(qū)域內(nèi)容</div>}
right={<div>右側(cè)區(qū)域內(nèi)容</div>}
gap={30}
>
<div>主區(qū)域內(nèi)容</div>
</ThreeLayout>,container);
demo2:制作一個(gè)蒙層組件
Modal文件夾
index.js文件
import React from 'react'
import './index.css'
export default function Modal(props) {
const defaultProps={
bg:'rgba(0,0,0,0.5)'
}
const datas=Object.assign({},defaultProps,props)
return (
// 點(diǎn)擊蒙層背景關(guān)閉蒙層
<div style={{background:datas.bg}} className='modal' onClick={(e)=>{
if(e.target.className==='modal'){//處理事件冒泡 只有點(diǎn)擊的是modal本身才關(guān)閉蒙層
datas.toggle(!datas.isShow)
}
}}>
<div className="modal-center">
{datas.children}
</div>
</div>
)
}
index.css文件
.modal{
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
}
.modal-center{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Test.jsx組件中使用:
import React, { Component } from 'react'
import Modal from './Modal'
export default class Test extends Component {
constructor(props){
super(props);
this.state={
showModal:false
}
this.handleToggle=this.handleToggle.bind(this)
}
handleToggle(){
this.setState({
showModal:!this.state.showModal
})
}
render() {
const img=<img style={{width:'100%'}} alt='向陽而生' src="https://tse4-mm.cn.bing.net/th/id/OIP-C.Mh_hsy1ou7stl89_Eol7XwHaHa?w=201&h=201&c=7&r=0&o=5&dpr=1.5&pid=1.7" />
return (
<div>
{img}
{this.state.showModal?(<Modal toggle={this.handleToggle} isShow={this.state.showModal}>
<button onClick={()=>this.handleToggle()}>關(guān)閉蒙層</button>
</Modal>):null}
<button style={{marginTop:'15px'}} onClick={()=>{this.handleToggle()}}>{this.state.showModal?'關(guān)閉蒙層':'打開蒙層'}</button>
</div>
)
}
}
今天就練習(xí)到這里了义黎,明天要繼續(xù)加油禾进!