在reactjs

时间:2016-07-30 03:32:52

标签: javascript reactjs ecmascript-6

我看到onChange监听器通常没有e以外的额外参数。

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

2 个答案:

答案 0 :(得分:6)

有几种方法可以做到这一点:

  1. 添加属性/或访问元素

    中的属性

    class FormInput扩展了Component {

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

    }

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

  3. <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
    
    1. 列表项
    2. 最后你可以包装元素,然后从那里传递调用者在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}/>
      

      希望这有帮助

答案 1 :(得分:3)

您可以创建一个匿名函数,使用自定义键调用handleOnChange。那看起来像是:

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

如果你以前没有使用过匿名函数,这就告诉JavaScript在渲染过程中动态创建一个新函数,它接受参数e并调用this.handleLogin(e,index)。在JavaScript中,匿名函数继承范围,因此“this”关键字的范围将正确。

相关问题