【问题标题】:Passing extra argument to onChange Listener in reactjs在reactjs中将额外的参数传递给onChange Listener
【发布时间】:2016-12-04 20:05:23
【问题描述】:

我看到一个 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>;
    }
}

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      使用此代码:

      class FormInput extends Component{
            onChange(e) {
                const { target } = e;
                const key = target.getAttribute('name');
            }
      }
      
      1. 在创建 onChange 函数时绑定额外的属性(部分)

      使用此代码:

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

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2018-10-07
        • 1970-01-01
        • 2011-03-06
        • 2021-02-27
        • 1970-01-01
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 2016-06-08
        相关资源
        最近更新 更多