我面临设置状态onChange的问题。
下面的handleChangeInputMobile只提供当前值,而不是当前目标。
对于移动号码字段验证,我尝试使用来自react-phone-number-input的react-phone-number-input。
但是我面临着更新州onChange的问题。
class Form extends Component {
state = {
data: {
firstName: "",
lastName: "",
mobile: "",
email: "",
password: "",
confirm_password: ""
},
errors: {},
disabled: true
};
handleChangeInputMobile({ currentTarget: input }) {
// I am not able to get current target here. It gives only value
const data = { ...this.state.data };
data[input.name] = input.value;
this.setState({ data });
}
render() {
const { mobile } = this.state.data;
<Mobile
handleChangeInputMobile={this.handleChangeInputMobile}
mobile={mobile}
/>;
}
}
export default Form;
import PhoneInput from "react-phone-number-input";
class Mobile extends Component {
render() {
const { handleChangeInputMobile } = this.props;
const { mobile } = this.props;
return (
<div>
<PhoneInput
country="IN"
id="mobile"
name="mobile"
value={mobile}
onChange={handleChangeInputMobile}
/>
</div>
);
}
}
export default Mobile;发布于 2019-08-05 14:25:39
根据文档的说法,
onChange PhoneInput的PhoneInput直接与value一起工作,您需要显式地发送name。
onChange={mobile => handleChangeInputMobile(mobile,"mobile")}你的handleChangeInputMobile函数应该是,
handleChangeInputMobile(value,key) {
this.setState(prevState => ({data: {...prevState.data, [key]: value}}), ()=> console.log(this.state))
}注意:您正在直接变异state,您应该使用prevState并更新您的状态,如上面所示。
同样在您的Form组件中,您忘记了return,可能是一个错误。
发布于 2019-08-05 13:06:25
尝试将input.value改为e.target.value,如下所示:
handleChangeInputMobile = (e) => {
this.setState({
[e.target.id]: e.target.value
})
}发布于 2019-08-05 14:02:44
您只能使用react-phone-number-input访问该值,因此您必须以param的形式传递您的密钥。
handleChangeInputMobile = (value, key) => {
this.setState({ [key]: value });
}
<PhoneInput
country="IN"
id="mobile"
name="mobile"
value={mobile}
onChange={value => handleChangeInputMobile(value, 'mobile')}
/>https://stackoverflow.com/questions/57359067
复制相似问题