【发布时间】:2021-10-21 14:45:02
【问题描述】:
我正在尝试通过该组件中函数内部的道具更改赋予组件的变量值。 我无法更改可观察对象的值(即使通过参数传递变量),所以我想知道是否可以检索可观察地址以直接修改它。
@observer
class Exemple extends React.Component {
@observable Nom
@action onChangeNom = newValue => {
this.Nom = newValue //I want to have something similar to this function inside the component but it would take the value to update and the newValue as parameters
}
render() {
return (
<FormComponent //this is where I call my component
ContainerStyle={{
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
}}
ObjArray={[
{
InputDivStyle: { width: '49%', marginRight: '2%' },
FieldType: 'textInput',
FieldStyle: { borderColor: this.missingLastName ? 'red' : COLOR_NOT_BLACK },
OnChange: this.onChangeNom,
Placeholders: 'Ex. Durand',
Value: this.Nom, //this is the value I want to change inside the component
InputTitle: 'Nom',
},
]}
/>
)
}
}
@observer
class FormComponent extends React.Component<props> {
render() {
const { ObjArray, ContainerStyle } = this.props
return (
<div style={ContainerStyle}>
{ObjArray.map((e, index: number) => {
const { Disabled, FieldStyle, InputDivStyle, FieldType, Placeholders, OnChange, Value, InputTitle } = e
return (
<>
<div style={InputDivStyle ?? {}} key={index + 'Input'}>
{InputTitle && (
<>
<Label medium>{InputTitle}</Label>
</>
)}
<GenericInput
disabled={Disabled ?? false}
placeholder={Placeholders ?? ''}
style={FieldStyle ?? {}}
type={FieldType ?? ''}
value={Value ?? ''}
onChange={evt => {
OnChange(evt.target.value)
}}
/>
</div>
</>
)
})}
</div>
)
}
}
export default FormComponent
我担心的是我希望能够更改组件内部的值,而不必为每个值创建一个函数(例如,如果 ObjArray 中有多个对象。(我已经尝试将值传递为组件内部的参数,但它不会在外部更新它,这就是为什么我希望能够直接在存储它的内存地址处更改值(就像你可以在 C 中使用指针一样)。
【问题讨论】:
-
恐怕你需要发布一些代码示例或调试细节,否则不清楚是什么问题。或者codesandbox.io复制,那是最好的
-
我编辑了帖子,我希望现在已经足够清楚了
标签: javascript reactjs mobx mobx-react