通过onChange事件传递附加参数 [英] Passing an additional parameter with an onChange event

查看:484
本文介绍了通过onChange事件传递附加参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做什么:

我试图将字符串从子组件传递到父组件的handleChange函数.

I am trying to pass a string from a child component to the handleChange function of a parent component.

当前有效的方法:

我有一个使用以下方法的父React JS类:

I have a parent React JS class with the following method:

handleChange(event) {

    console.log(event.target.value);
}

在渲染功能中,我有以下内容:

In the render function I have the following:

<Child handleChange={this.handleChange.bind(this)} />

在Child班上,我有:

In the Child class I have:

<fieldset onChange={this.props.handleChange}>
    <div>Tag 1: <input id="tag1" value={tags[0]} /></div>
    <div>Tag 2: <input id="tag2" value={tags[1]} /></div>
    <div>Tag 3: <input id="tag3" value={tags[2]} /></div>
</fieldset>

这很好.

我正在尝试做的事情:

我试图将section参数添加到handleChange函数,如下所示:

I am attempting to add a section parameter to the handleChange function as follows:

handleChange(section, event) {
    console.log(section);
    console.log(event.target.value);
}

在Child类中,我有:

And in the Child class I have:

<fieldset onChange={this.props.handleChange("tags")}>
    <div>Tag 1: <input id="tag1" value={tags[0]} /></div>
    <div>Tag 2: <input id="tag2" value={tags[1]} /></div>
    <div>Tag 3: <input id="tag3" value={tags[2]} /></div>
</fieldset>

我现在收到错误:

Uncaught TypeError: Cannot read property 'target' of undefined

此错误正在我的第二个console.log语句中引发.

This error is being thrown in my second console.log statement.

我做错了什么?

此外,我正在考虑将section参数设置为可选.如果是这样,有没有简单的方法可以做到这一点?如果事件参数需要最后一个,这似乎是不可能的.

Also, I am considering making the section parameter optional. If so, is there an easy way to do this? It seems like it might not be possible if the event parameter needs to be last.

推荐答案

在编写此代码时:

<fieldset onChange={this.props.handleChange("tags")}>

handleChange将在触发渲染后立即被调用.

handleChange will be called immediately as soon as render is triggered.

相反,请这样做:

<fieldset onChange={(e) => this.props.handleChange("tags", e)}>

现在,当调用onChange处理程序时,将调用handleChange.

Now the handleChange will be called when onChange handler is called.

这篇关于通过onChange事件传递附加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆