gpt4 book ai didi

javascript - MOBX 默认的、从其他状态派生的可编辑状态

转载 作者:太空宇宙 更新时间:2023-11-04 15:44:02 25 4
gpt4 key购买 nike

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

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

react 组件(原因):

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},您要求 ${amount} X ${color} ${product},我该怎么做。我不能为此使用计算函数,因为用户必须能够覆盖原因。当然,每次用户更新默认字符串中显示的字段之一时,默认字符串都需要更新。

提前致谢

最佳答案

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

示例 ( 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>;
}
}

关于javascript - MOBX 默认的、从其他状态派生的可编辑状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43681429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com