简体   繁体   中英

React using method parameter as an object key to update state

How can I use a function parameter as a property name to update state ie

onStudentPinChange = (propertyName, e) => {
    this.setState({
      formFields: { ...this.state.formFields, propertyName: e.target.value }
    });
};

the code above throw error

I would like to use that propertyName variable as an object key I googled and tried many different techniques like this.state.formFields[propertName]

I am creating a new web-app I have a few form fields which needed to be filled to login to the admin area. I have three methods which are basically doing the same thing just updating the relevant state

onStudentPinChange = (propertyName, e) => {
    var item = { ...this.state.formFields };
    item[propertyName] = e.target.value;
    console.log(item);
    this.setState({
      formFields: { ...this.state.formFields, studentPin: e.target.value }
    });
  };

  onCNICChange = (propertyName, e) => {
    this.setState({
      formFields: { ...this.state.formFields, cnic: e.target.value }
    });
  };

  onPasswordChange = (propertyName, e) => {
    this.setState({
      formFields: { ...this.state.formFields, password: e.target.value }
    });
  };



<InputField
        type="text"
        name="student_pin"
        value={this.state.formFields.studentPin}
        placeholder="Student Pin"
        onChange={this.onStudentPinChange.bind(this, "studentPin")}
        faClassName="fa-user"
      />

I would like only to have one function that updates all three fields just using that properName

Regards

Welcome to StackOverflow. You can achieve this by wrapping property name around brackets so that it evaluates the key as a variable and not actually propertyName.

onStudentPinChange = (propertyName, e) => {
    this.setState({
        formFields: {
            ...this.state.formFields,
            [propertyName]: e.target.value
        }
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM