失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > react给Input绑定onChange事件

react给Input绑定onChange事件

时间:2019-08-07 16:33:03

相关推荐

react给Input绑定onChange事件

最近学习react,绑定事件时遇到了一点小问题,直接上代码:

class PageList extends ponent {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><Popconfirmtitle="确定要删除吗?"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><DragModalvisible = {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 ponent {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><Popconfirmtitle="确定要删除吗?"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><DragModalvisible = {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>);}}

如果觉得《react给Input绑定onChange事件》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。