首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获取对象的密钥名并更新相应的键状态

如何获取对象的密钥名并更新相应的键状态
EN

Stack Overflow用户
提问于 2019-08-05 12:56:43
回答 3查看 700关注 0票数 0

我面临设置状态onChange的问题。

下面的handleChangeInputMobile只提供当前值,而不是当前目标。

对于移动号码字段验证,我尝试使用来自react-phone-number-inputreact-phone-number-input

但是我面临着更新州onChange的问题。

代码语言:javascript
复制
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;
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-08-05 14:25:39

根据文档的说法,

onChange PhoneInputPhoneInput直接与value一起工作,您需要显式地发送name

代码语言:javascript
复制
onChange={mobile => handleChangeInputMobile(mobile,"mobile")}

你的handleChangeInputMobile函数应该是,

代码语言:javascript
复制
handleChangeInputMobile(value,key) {
    this.setState(prevState => ({data: {...prevState.data, [key]: value}}), ()=> console.log(this.state)) 
}

注意:您正在直接变异state,您应该使用prevState并更新您的状态,如上面所示。

同样在您的Form组件中,您忘记了return,可能是一个错误。

演示

票数 1
EN

Stack Overflow用户

发布于 2019-08-05 13:06:25

尝试将input.value改为e.target.value,如下所示:

代码语言:javascript
复制
handleChangeInputMobile = (e) => {

 this.setState({
    [e.target.id]: e.target.value
  })

}
票数 3
EN

Stack Overflow用户

发布于 2019-08-05 14:02:44

您只能使用react-phone-number-input访问该值,因此您必须以param的形式传递您的密钥。

代码语言:javascript
复制
handleChangeInputMobile = (value, key) => {
 this.setState({ [key]: value });
}

<PhoneInput
  country="IN"
  id="mobile"
  name="mobile"
  value={mobile}
  onChange={value => handleChangeInputMobile(value, 'mobile')}
/>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57359067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档