我在一个input元素上同时处理state-management和event management时遇到了麻烦。
import React, { Component } from 'react';
export class profileDetail extends Component {
continue = (e) => {
e.preventDefault();
this.props.nextStep();
};
back = (e) => {
e.preventDefault();
this.props.prevStep();
};
render() {
const { values, handleChange } = this.props;
const imageHandler = () => {
//Do this thing..
//make this magic happen...
};
return (
<div>
Add your Profile Picture:
<input
-----HERE------> onChange={handleChange('ProfilePic')}
& defaultValue={values.ProfilePic}
-----HERE------> onChange={imageHandler}
type="file"
name="inpFile"
id="inpFile"
accept="image/*"
/>
</div>
);
}
}
export default profileDetail;如果我像上面那样在一个输入上添加两个onChange,要么我碰巧让状态管理正常工作,要么是带有onchange的DOM操作可以正常工作,而不是两者都起作用。
那么,我应该如何以及如何进行更改才能使其正常工作呢?
发布于 2020-05-06 21:50:09
尝试在相同的函数中使用它们,如onChange。
另外,请注意组件的名称应该是大写的,这样它就不会被视为HTML元素。
export class ProfileDetails extends Component {
imageHandler = () => {
/* ... */
};
onChange = () => {
this.imageHandler();
this.props.handleChange("ProfilePic");
};
render() {
const { values } = this.props;
return (
<input
onChange={this.onChange}
defaultValue={values.ProfilePic}
type="file"
name="inpFile"
id="inpFile"
accept="image/*"
/>
);
}
}发布于 2020-05-06 21:52:56
export class profileDetail extends Component {
continue = (e) => {
e.preventDefault();
this.props.nextStep();
imageHandler = imageHandler.bind(this);
};
back = (e) => {
e.preventDefault();
this.props.prevStep();
};
const imageHandler = () => {
//Do this thing..
//make this magic happen...
//and then call outer handler
this.props.handleChange('ProfilePic');
};
render() {
const { values } = this.props;
return (
<div>
Add your Profile Picture:
<input
defaultValue={values.ProfilePic}
onChange={imageHandler}
type="file"
name="inpFile"
id="inpFile"
accept="image/*"
/>
</div>
);
}
}发布于 2020-05-06 21:54:00
您可以使用匿名函数将要调用的两个方法组合到一个处理程序中:
<input
onChange={() => {
handleChange('ProfilePic');
imageHandler();
}}
defaultValue={values.ProfilePic}
type="file"
name="inpFile"
id="inpFile"
accept="image/*"/>https://stackoverflow.com/questions/61636851
复制相似问题