Red*_*ant 4 javascript ecmascript-6 reactjs
我看到一个onChange监听器通常没有额外的参数e.
handleOnChange(e) {
this.setState({email: e.target.value});
}
Run Code Online (Sandbox Code Playgroud)
但是仍然可以通过额外的论点吗?像这样:
handleOnChange(e,key) {
this.setState({[key]: e.target.value});
}
Run Code Online (Sandbox Code Playgroud)
我修改了这个线程中的代码来做一个例子
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>;
}
}
Run Code Online (Sandbox Code Playgroud)
几种方法:
添加属性/或从元素访问属性
class FormInput扩展Component {
onChange(e) {
const { target } = e;
const key = target.getAttribute('name');
}
Run Code Online (Sandbox Code Playgroud)
}
在创建onChange函数时绑定额外属性(partials)
Run Code Online (Sandbox Code Playgroud)<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
Run Code Online (Sandbox Code Playgroud)
最后,您可以包装元素,然后从那里传递调用者在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}/>
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
1787 次 |
| 最近记录: |