如何将多个 mobx 观察者状态作为参数传递给函数
How to pass multiple mobx observer states into function as parameter
我有这些状态:
@observable questionString: string = '';
@observable questionLengthRemaining: number = 25;
@observable descriptionString: string = '';
@observable descriptionLengthRemaining: number = 500;
我有这个功能:
onInputChamge = (state: any, stateLengthRemaining: any, maxLength: any, text: string) => {
state = text;
stateLengthRemaining = maxLength - text.length;
}
这是我的组件:
<TextInput
multiline={true}
maxLength={questionMaxLength}
placeholder='Type your question here'
style={styles.questionInput}
onChangeText={(question) => this.onInputChamge(this.questionString, this.questionLengthRemaining, questionMaxLength, question)}
/>
我有多个 textInputs,它们只需要做同样的事情并接收 onInputChange 函数,只是状态和长度不同。出于某种原因,在函数中将状态作为参数传递是行不通的,但是当我为每个状态创建不同的函数时,例如:
onQuestionChange = (text: string) => {
this.questionString = text;
this.questionLengthRemaining = maxQuestionLength - text.length;
}
有效。
为每个输入创建相同的函数是毫无意义的,因为那是函数应该限制的。顺便说一下,我正在使用 typescript 和 mobx。有什么办法吗? (如果我控制台记录剩余的长度,它会打印出正确的数字和字符串,所以我知道发生了什么)
如果所有 observable
都在同一个 class 组件中,那么您可以这样做:
onInputChange = (key, value, stateLengthRemaining, maxLength, text) => {
this[key] = value
}
然后像那样传递 属性 的名称 question => this.onInputChange('questionString', question, ... )
你也不需要手动分配 descriptionLengthRemaining
因为你可以让它计算 属性 https://mobx.js.org/refguide/computed-decorator.html
@computed get questionLengthRemaining() {
return 25 - this.questionString.length
};
我有这些状态:
@observable questionString: string = '';
@observable questionLengthRemaining: number = 25;
@observable descriptionString: string = '';
@observable descriptionLengthRemaining: number = 500;
我有这个功能:
onInputChamge = (state: any, stateLengthRemaining: any, maxLength: any, text: string) => {
state = text;
stateLengthRemaining = maxLength - text.length;
}
这是我的组件:
<TextInput
multiline={true}
maxLength={questionMaxLength}
placeholder='Type your question here'
style={styles.questionInput}
onChangeText={(question) => this.onInputChamge(this.questionString, this.questionLengthRemaining, questionMaxLength, question)}
/>
我有多个 textInputs,它们只需要做同样的事情并接收 onInputChange 函数,只是状态和长度不同。出于某种原因,在函数中将状态作为参数传递是行不通的,但是当我为每个状态创建不同的函数时,例如:
onQuestionChange = (text: string) => {
this.questionString = text;
this.questionLengthRemaining = maxQuestionLength - text.length;
}
有效。
为每个输入创建相同的函数是毫无意义的,因为那是函数应该限制的。顺便说一下,我正在使用 typescript 和 mobx。有什么办法吗? (如果我控制台记录剩余的长度,它会打印出正确的数字和字符串,所以我知道发生了什么)
如果所有 observable
都在同一个 class 组件中,那么您可以这样做:
onInputChange = (key, value, stateLengthRemaining, maxLength, text) => {
this[key] = value
}
然后像那样传递 属性 的名称 question => this.onInputChange('questionString', question, ... )
你也不需要手动分配 descriptionLengthRemaining
因为你可以让它计算 属性 https://mobx.js.org/refguide/computed-decorator.html
@computed get questionLengthRemaining() {
return 25 - this.questionString.length
};