1. 父子组件通信
在上一小节《React基础—PropTypes
类型检查》中已经定义了父、子组件,接下来的工作就将在这个案例上做拓展。
比如这里为列表右侧添加一个删除按钮,然后点击后删除本项条目。根据组件化的思想,且还未涉及到其余的父子控件传递数据(通信)的方式,这里就需要使用传递回调函数的方式来处理,也就是:
- 在父控件中定义回调函数方法,然后通过
props
传递这个函数到子控件中; - 由子控件触发具体的事件函数,然后调用父控件传递的回调函数,通过参数传递本条数据的标识;
比如下面的代码:
// 子组件
class Item extends Component {
constructor() {
super();
this.state = {
isHover: false}
}
handleDel = () => {
// 向父控件发送请求,请求删除数据
this.props.handleDelete(this.props.data.id)
}
handleMouseOver = () => {
this.setState({
isHover: true})
}
handleMouseOut = () => {
this.setState({
isHover: false})
}
render() {
const {
data} = this.props
const {
isHover} = this.state
return (
<div style={
{
display: "flex", flexDirection: "row", lineHeight: '1rem', width: '200px', padding: '8px'}}
className={
isHover ? 'hoverStyle' : 'defaultStyle'}
onMouseOver={
this.handleMouseOver}
onMouseOut={
this.handleMouseOut}
>
<div style={
{
flex: 1}}>{
data.name}</div>
<div className={
isHover ? 'delStyleHover' : 'delStyleDefault'} onClick={
this.handleDel}>删除</div>
</div>
)
}
}
// 可以限制一下传入子组件的参数的类型
Item.propTypes = {
data: PropTypes.object.isRequired
}
class PropTypesDemo extends Component {
constructor() {
super();
this.state = {
datas: [
{
id: '001', name: "张三"},
{
id: '003', name: "李四"},
{
id: '002', name: "王五"},
]
}
}
handleDelete = (id) => {
// 删除id的数据
const {
datas} = this.state
let temp_array = datas.filter((item) => {
return item.id !== id
})
this.setState({
datas: temp_array})
}
render() {
const {
datas} = this.state
return (
<div>
{
datas.map((item, index) => {
return <Item key={
item.id} data={
item} handleDelete={
this.handleDelete}/>
})
}
</div>
);
}
}
对应的css
代码:
.hoverStyle {
background: #d4d4d4;
cursor: pointer;
}
.defaultStyle {
background: white
}
.delStyleHover{
color:red;
margin-left: 1.5rem;
text-align: right;
cursor: pointer
}
.delStyleDefault{
color:white;
margin-left: 1.5rem;
text-align: right;
}
效果: