Estoy tratando de cambiar un valor de variable dado a un componente a través de accesorios dentro de una función en este componente. No puedo cambiar el valor del observable (incluso cuando paso la variable a través del parámetro), así que quería saber si podía recuperar la dirección observable para modificarla directamente de esta manera.
@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 FormComponentMi preocupación es que quiero poder cambiar el valor dentro del componente sin tener que crear una función para cada valor (si hubiera varios objetos en ObjArray, por ejemplo). (Ya lo intenté pasando el valor como parámetros dentro de el componente pero no lo actualiza fuera, por eso quiero poder cambiar el valor directamente en la dirección de memoria donde está almacenado (como se puede hacer en C con punteros)).
Quiero poder cambiar el valor directamente en la dirección de memoria donde está almacenado
No es posible en Javascript, no puede "pasar por referencia" (en el significado original) y, por lo tanto, no puede cambiar valores así.
La forma más fácil sería tener una función como esa:
@action onChange = (key, newValue) => { this[key] = newValue }Lo pasas al componente con una clave y luego lo invocas así:
onChange={evt => { // Or you can use InputTitle instead of key OnChange(key, evt.target.value) }}De esa manera, no necesita crear muchas funciones para cada valor