2016-07-30 99 views
3

我看到一个onChange监听器通常不会有除e以外的额外参数。传递额外的参数给onChange监听器在reactjs

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

但是仍然可以传递额外的参数吗?就像这样:

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

我修改了代码从this thread做出了榜样

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>; 
    } 
} 

回答

3

您可以创建一个匿名函数,调用handleOnChange您的自定义键。这将是这样的:

<button type="button" onClick={(e) => this.handleLogin(e, index)}> 

如果你还没有使用匿名函数之前,这是告诉JavaScript的合作,动态创建一个新的功能中呈现,这需要一个参数e和调用this.handleLogin(E,指数)。在JavaScript中,匿名函数会继承范围,所以“this”关键字的范围将会正确。

+0

美妙的解决方案。谢谢。 – Shwe

6

几个方法可以做到这一点:

  1. 添加属性/或元素

    类的formInput扩展组件{

    onChange(e) { 
        const { target } = e; 
        const key = target.getAttribute('name'); 
    } 
    

    }

  2. 访问属性

    在创建onChange函数时绑定额外的属性(部分)

<input name='password' onChange={this.onChange.bind('password')} /> 
//or 
<input name='password' onChange={(e) => this.onChange('password',e)} /> 
Do note that you would need to change the order of the onChange function 

onChange(key,e) { 
    //key is passed here 
} 


This is usually not advisable because you would create the function on each render call. See if its fine on your case 
  • 列表项
  • 最后你可以用的元素,并从那里只是通过什么调用者需要在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}/> 
    

    希望这有助于

    相关问题