最近学习react,绑定事件时遇到了一点小问题,直接上代码:
class PageList extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: false
}
}
changeEvent(event) {
const name = event.target.name;
const value = event.target.value;
console.log("name = " + name + ", value =" + value)
this.setState({
[name]: value
})
}
render() {
const { data } = this.props;
const columns = [
{
title: "校区代码",
dataIndex: "xqdm",
key: "xqdm"
},
{
title: "校区名称",
dataIndex: "xqmc",
key: "xqmc"
},
{
title: "操作",
key: "action",
render: (text, item) => {
return (
<span>
<Popconfirm
title="确定要删除吗?"
onConfirm={() => this.doDelete(item.xqdm)}
>
<a>删除</a>
</Popconfirm>
<Divider type="vertical" />
<a onClick={() => this.edit(item)}>编辑</a>
</span>
);
}
}
];
return (
<div>
<div className="operation-btns">
<Button type="primary" onClick={() => this.handleAdd()}>
新增
</Button>
</div>
<DragModal
visible = {this.state.visible}
title = "校区信息"
onOk = {() => {
message.success("添加成功");
this.setState({
visible: false
});
console.log(this.state)
}}
onCancel = {() => {
this.setState({
visible: false
});
}}
>
校区代码:<Input name = "xqdm" onChange={() => this.changeEvent} />
校区名称:<Input name = "xqmc" onChange={() => this.changeEvent} />
</DragModal>
<Table loading={false} columns={columns} dataSource={data} />
</div>
);
}
}
以上代码发现绑定事件并没有被执行,控制台也不报错,一时间不知道怎么办,直到看到添加按钮的点击事件,函数调用写了(),于是猜测可能与没有写括号有关。
<div className="operation-btns">
<Button type="primary" onClick={() => this.handleAdd()}>
新增
</Button>
</div>
果然,换一种写法,问题解决了,仔细想一下,通过onChange={() => this.changeEvent}这种方式绑定事件,箭头后面的内容是方法体,方法体中方法没有写圆括号,导致没有调用到changeEvent()方法,但是浏览器控制台并没有提示,由于事件方法都有一个event参数,为了方便,方法定义使用箭头函数的方式。
以下代码为正确代码:
class PageList extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: false
}
}
changeEvent = (event) => {
const name = event.target.name;
const value = event.target.value;
console.log("name = " + name + ", value =" + value)
this.setState({
[name]: value
})
}
render() {
const { data } = this.props;
const columns = [
{
title: "校区代码",
dataIndex: "xqdm",
key: "xqdm"
},
{
title: "校区名称",
dataIndex: "xqmc",
key: "xqmc"
},
{
title: "操作",
key: "action",
render: (text, item) => {
return (
<span>
<Popconfirm
title="确定要删除吗?"
onConfirm={() => this.doDelete(item.xqdm)}
>
<a>删除</a>
</Popconfirm>
<Divider type="vertical" />
<a onClick={() => this.edit(item)}>编辑</a>
</span>
);
}
}
];
return (
<div>
<div className="operation-btns">
<Button type="primary" onClick={() => this.handleAdd()}>
新增
</Button>
</div>
<DragModal
visible = {this.state.visible}
title = "校区信息"
onOk = {() => {
message.success("添加成功");
this.setState({
visible: false
});
console.log(this.state)
}}
onCancel = {() => {
this.setState({
visible: false
});
}}
>
校区代码:<Input name = "xqdm" onChange={this.changeEvent} />
校区名称:<Input name = "xqmc" onChange={this.changeEvent} />
</DragModal>
<Table loading={false} columns={columns} dataSource={data} />
</div>
);
}
}