MOBX 默认,从其他状态派生的可编辑状态

MOBX Default, editable state derived from other states

假设我有一个表单,用户需要在其中添加个人信息(姓名、名字和邮件)、输入产品、数量、颜色和原因。

class Store {
    constructor(){
        extendObservable(this, {
             name : '', 
             firstName : '', 
             mail: '', 
             product : '', 
             amount: 0, 
             color: '', 
             reason : '',
             // computed functions & actions... 
        })
    }
}

反应组件(原因):

const Reason = observer(class Reason extends Component {
    onChange = (e) => {
        this.props.store.setReason(e.target.value);
    };  

    render () {
        const reason = this.props.store.reason;

        return (
             <textarea
                id="reason"
                name="reason"
                className="form-control"
                required={true}
                onChange={this.onChange}
                rows="2"
                value={reason}
             />
        );
    }
});

如果我想添加默认原因,例如 Hi ${firstName}, you asked for ${amount} X ${color} ${product},我该怎么做。我不能为此使用计算函数,因为用户必须能够覆盖原因。当然,每次用户更新默认字符串中显示的字段之一时,默认字符串都需要更新。

提前致谢

您可以为此使用计算。您可以使用布尔值来检查用户是否更改了原因。

示例 (JSBin)

class State {
  @observable reason = '';
  @observable editedReason = false;
  @observable firstname = 'Carl';
  @observable amount = 2;
  @observable color = 'red';
  @observable product = 'car';
  @computed get computedReason() {
    return this.editedReason
      ? this.reason
      : `Hi ${this.firstname}, you asked for ${this.amount} X ${this.color} ${this.product}`;
  }
}

const state = new State();

@observer
class App {
  onChange = (e) => {
    state.editedReason = true;
    state.reason = e.target.value;
  }

  render() {
    return <div>
      <textarea
        onChange={this.onChange}
        value={state.computedReason}
      />
    </div>;
  }
}