尝试使用mobX替换setState

问题描述 投票:0回答:1

试图在react中替换setState。有问题在mobX中使用observable改变this.info的值。当我在console.log(e.target.name,e.target.value)时,该值只返回一个字母。

//Login
import * as React from 'react';
import { extendObservable } from 'mobx';
import { observer }  from 'mobx-react';

constructor(props) {
        super(props);

        extendObservable(this, {
            info: {
                username: '',
                password: ';
            }
        })
    }

onChange = (name, value) => {
    this.info[name] = value
}

render(){
    <LoginForm info={this.info} onChange={this.onChange}/>
}
//LoginForm
import * as React from 'react';
import {Form} from "semantic-ui-react";

const onChange = (props) => (e) => {
    props.onChange(e.target.name, e.target.value)
    console.log(e.target.name, e.target.value)
};

const LoginForm = (props) => {
    return (
                    <Form.Input fluid label='username' placeholder='username' name="username"
                                value={props.info.username|| ''}
                                onChange={onChange(props)} type="text" />
                    <Form.Input fluid label='password' placeholder='password' name="password"
                                value={props.info.passoword || ''}
                                onChange={onChange(props)} type="text"/>
    )
}


javascript mobx mobx-react mobx-react-form
1个回答
1
投票

试试这个怎么样?更改信息对象而不是对象中的值

import { action, extendObservable } from "mobx";
onChange = action((name, value) => {
  this.info = { ...this.info , [name]: value };
});
© www.soinside.com 2019 - 2024. All rights reserved.