react核心概念-传递元素
2023-08-07 本文已影响0人
5cc9c8608284
传递元素内容
内置组件:div、h1、p
<div>
asdfafasfafasdfasdf
</div>
如果给自定义组件传递元素内容,则React会将元素内容作为children属性传递过去。
练习
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>左侧区域内容</div>}
right={<div>右侧区域内容</div>}
gap={30}
>
<div>主区域内容</div>
</ThreeLayout>,container);
demo2:制作一个蒙层组件
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 (
// 点击蒙层背景关闭蒙层
<div style={{background:datas.bg}} className='modal' onClick={(e)=>{
if(e.target.className==='modal'){//处理事件冒泡 只有点击的是modal本身才关闭蒙层
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()}>关闭蒙层</button>
</Modal>):null}
<button style={{marginTop:'15px'}} onClick={()=>{this.handleToggle()}}>{this.state.showModal?'关闭蒙层':'打开蒙层'}</button>
</div>
)
}
}
今天就练习到这里了,明天要继续加油!