children(插槽)
- children的作用类似于Vue中插槽的概念。
- children属性名固定,它是React的核心API。
class Test extends React.Component {
render () {
return (
<div>
<div>测试Children:</div>
<div>{this.props.children}</div>
</div>
)
}
}
class ChildrenTest extends React.Component {
render () {
return (
<div>
<h1>children属性的用法</h1>
<hr/>
{}
<Test>
<div>Tom</div>
<div>Jerry</div>
</Test>
</div>
)
}
}
弹窗组件封装
- 基于children属性进行封装
- 封装时一般会把容易发生变化的特性提取到组件属性中,这样别人在使用组件时,可以动态设置相应的值。
import React from 'react'
import './MyBox.css'
class MyBox extends React.Component {
hideBox = () => {
this.props.closeBox()
}
render () {
const { isShow, boxName, titleColor } = this.props
return (
<div className={isShow?'': 'box'}>
{}
<div className="bg"></div>
{}
<div className="win">
<div className="title" style={{backgroundColor: titleColor? titleColor: 'lightblue'}}>
<div className="name">{boxName}</div>
<div onClick={this.hideBox} className="close">X</div>
</div>
{}
<div>
{this.props.children}
</div>
</div>
</div>
)
}
}
class MyBoxTest extends React.Component {
state = {
isShow: false
}
showBox = () => {
this.setState({
isShow: true
})
}
closeBox = () => {
this.setState({
isShow: false
})
}
render () {
return (
<div>
<h1>测试弹窗组件</h1>
<hr/>
<button onClick={this.showBox}>显示弹窗</button>
<MyBox
titleColor='orange'
boxName='添加商品'
closeBox={this.closeBox}
isShow={this.state.isShow}>
<div>
<label htmlFor="uname">用户名:</label>
<input type="text" id="uname"/>
</div>
<div>
<label htmlFor="pwd">密码:</label>
<input type="text" id="pwd"/>
</div>
<div>
<button>确定</button>
</div>
</MyBox>
</div>
)
}
}
export default MyBoxTest