在Reactjs中传递额外的参数到onChange监听器

4

我发现onChange监听器通常除了e参数之外没有其他额外的参数。

handleOnChange(e) {
   this.setState({email: e.target.value});
}

但是是否仍然可以传递额外的参数?像这样:
handleOnChange(e,key) {
   this.setState({[key]: e.target.value});
}

我修改了这个帖子中的代码,以便制作一个示例。

class FormInput extends React.Component{

    consturctor(props){
       super(props);
       this.state = {email:false,password:false}
    }

    handleOnChange(e,key) {
       this.setState({[key]: e.target.value});
    }

    render() {
          return 
            <form>
              <input type="text" name="email" placeholder="Email" onChange={this.handleOnChange('email')} />
              <input type="password" name="password" placeholder="Password" onChange={this.handleOnChange('password')}/>
              <button type="button" onClick={this.handleLogin}>Zogin</button>
            </form>;
    }
}
2个回答

9
以下是几种方法:
  1. 添加属性或从元素中访问属性
使用以下代码:
class FormInput extends Component{
      onChange(e) {
          const { target } = e;
          const key = target.getAttribute('name');
      }
}
  1. 在创建onChange函数时绑定额外的属性(partials)

使用以下代码:

<input name='password' onChange={this.onChange.bind('password')} />
//or
<input name='password' onChange={(e) => this.onChange('password',e)} />

请注意,您需要更改onChange函数的顺序。
onChange(key,e) {
   //key is passed here
}

通常不建议这样做,因为每次渲染都会创建函数。请根据您的情况进行判断。

  1. 列表项

最后,您可以将元素包装起来,然后只需传递调用者在onChange时需要的内容。

class Input extends Component {

       dispatchOnChange(e) {
           const { props } = this;
           const { name } = props;
           const value = e.target.value;
           props.onChange(name,value);
       }

       render() {
           return <input {...this.props} onChange={this.dispatchOnChange}/>
       }
   }

   //your render
   <Input type="password" name="password" placeholder="Password" onChange={this.handleOnChange}/>

希望这可以帮助到您。

4
您可以创建一个匿名函数,调用handleOnChange,并使用您自定义的键。看起来像这样:
<button type="button" onClick={(e) => this.handleLogin(e, index)}>

如果您以前没有使用过匿名函数,那么这个代码告诉JavaScript在渲染期间创建一个新的函数,该函数接受一个参数e并调用this.handleLogin(e, index)。在JavaScript中,匿名函数继承作用域,因此关键字"this"将被正确地作用于当前范围内。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接