假设我有一个表单,用户需要添加他的个人信息(姓名,名字和邮件),输入产品,数量,颜色和原因。
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}
,我该怎么做。我无法使用计算函数,因为用户必须能够覆盖原因。当然,每当用户更新默认字符串中显示的某个字段时,默认字符串都需要更新。
提前致谢
答案 0 :(得分:1)
您可以使用计算结果。您可以使用布尔值来检查用户是否更改了原因。
示例(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>;
}
}