Pregunta

Mi estado es:

[
  {type: "translateX", x: 10},
  {type: "scaleX", x: 1.2}
]

Estoy usando Ayudantes de encuadernación bidireccional y no puedo proporcionar una cadena de clave válida para linkState:

this.state.map(function(item, i) {
  return <div><input valueLink={this.linkState( ??? )}></div>
}

Sería bueno si this.linkState aceptó alguna sintaxis de consulta, como "0.type" recuperar "translateX" de mi ejemplo.

¿Hay alguna solución?


escribí Mezcla de DeepLinkState que es un reemplazo directo de React.addons.LinkedStateMixin.Ejemplo de uso:

this.state.map(function(item, i) {
  return <div><input valueLink={this.linkState([i, "x"])}></div>
}

linkState("0.x") También es una sintaxis aceptable.

¿Fue útil?

Solución

Editar:

Me di cuenta de que el camino profundo para LinkedState es bastante bueno, así que trato de implementarlo.
El código: https://gist.github.com/tungd/8367229
Uso: http://jsfiddle.net/uHm6k/3/


Como decía el documento, LinkedState es una envoltura alrededor onChange/setState y destinado a casos simples.Siempre puedes escribir el completo. onChange/setState para lograr lo que deseas.Si realmente quieres seguir con LinkedState, puedes usar la versión no mixin, por ejemplo:

getInitialState: function() {
    return { values: [
        { type: "translateX", x: 10 },
        { type: "scaleX", x: 1.2 }
    ]}
},
handleTypeChange: function(i, value) {
    this.state.values[i].type = value
    this.setState({ values: this.state.values })
},
render: function() {
    ...
    this.state.values.map(function(item, i) {
        var typeLink = {
            value: this.state.values[i].type,
            requestChange: this.handleTypeChange.bind(null, i)
        }
        return <div><input valueLink={typeLink}/></div>
    }, this)
    ...
}

Aquí está trabajando JSFiddle: http://jsfiddle.net/srbGL/

Otros consejos

Puedes implementar tu propio mixin si el mixin base no te satisface.

Vea cómo se implementa este mixin:

var LinkedStateMixin = {
  /**
   * Create a ReactLink that's linked to part of this component's state. The
   * ReactLink will have the current value of this.state[key] and will call
   * setState() when a change is requested.
   *
   * @param {string} key state key to update. Note: you may want to use keyOf()
   * if you're using Google Closure Compiler advanced mode.
   * @return {ReactLink} ReactLink instance linking to the state.
   */
  linkState: function(key) {
    return new ReactLink(
      this.state[key],
      ReactStateSetters.createStateKeySetter(this, key)
    );
  }
};

/**
 * @param {*} value current value of the link
 * @param {function} requestChange callback to request a change
 */
function ReactLink(value, requestChange) {
  this.value = value;
  this.requestChange = requestChange;
}

https://github.com/facebook/react/blob/fc73bf0a0abf739a9a8e6b1a5197dab113e76f27/src/addons/link/LinkedStateMixin.js https://github.com/facebook/react/blob/fc73bf0a0abf739a9a8e6b1a5197dab113e76f27/src/addons/link/ReactLink.js

Para que puedas intentar escribir el tuyo propio fácilmente. linkState función basada en lo anterior.

linkState: function(key,key2) {
  return new ReactLink(
    this.state[key][key2],
    function(newValue) {
      this.state[key][key2] = newValue;
    }
  );
}

Note que no usé el ReactStateSetters.createStateKeySetter(this, key). https://github.com/facebook/react/blob/fc73bf0a0abf739a9a8e6b1a5197dab113e76f27/src/core/ReactStateSetters.jsAl mirar el código fuente nuevamente, podrá descubrir que este método no hace mucho excepto que crea una función y realiza pequeñas optimizaciones de almacenamiento en caché:

function createStateKeySetter(component, key) {
  // Partial state is allocated outside of the function closure so it can be
  // reused with every call, avoiding memory allocation when this function
  // is called.
  var partialState = {};
  return function stateKeySetter(value) {
    partialState[key] = value;
    component.setState(partialState);
  };
}

Así que definitivamente deberías intentar escribir tu propio mixin.Esto puede ser muy útil si tienes en tu estado un objeto complejo y quieres modificarlo a través de la API del objeto.

Lo hago sin usar el complemento value-link.

Aquí hay una demostración: http://wingspan.github.io/wingspan-forms/examples/form-twins/

El secreto es definir solo una función onChange:

onChange: function (path, /* more paths,*/ value) {
    // clone the prior state
    // traverse the tree by the paths and assign the value
    this.setState(nextState);
}

úsalo así:

<input 
    value={this.state['forms']['0']['firstName']} 
    onChange={_.partial(this.onChange, 'forms', '0', 'firstName')} />

si tienes muchos (value, onChange) pares que tienes que pasar por todas partes, podría tener sentido definir una abstracción en torno a esto similar a ReactLink, pero personalmente llegué bastante lejos sin usar ReactLink.

Mis colegas y yo abrimos recientemente formas de envergadura, una biblioteca de React que ayuda con el estado profundamente anidado.Aprovechamos mucho este enfoque.Puede ver más demostraciones de ejemplo con estado vinculado en la página de github.

Escribí un blogpost al respecto: http://blog.sendsonar.com/2015/08/04/angular-like-deep-path-data-bindings-in-react/

Pero básicamente creé un nuevo componente que aceptaría el 'estado' de los padres y un camino profundo, por lo que no tiene que escribir código extra.

<MagicInput binding={[this, 'account.owner.email']} />

También hay un jsfiddle para que puedas jugar con él

Aquí está el tutorial que explica cómo manejar cosas como esta.

Estado y formularios en React, Parte 3:Manejando el estado complejo

TL;DR:

0) No utilice enlaces estándar.Usar estos.

1) Cambia tu estado para que se vea así:

collection : [
  {type: "translateX", x: 10},
  {type: "scaleX", x: 1.2}
]

2) Tome el enlace al collection:

var collectionLink = Link.state( this, 'collection' );

3) Iterar a través de los enlaces a sus elementos:

collectionLink.map(function( itemLink, i ) {
  return <div><input valueLink={itemLink}></div>
})

Tomé un enfoque diferente que no emplea a Mixins y no muta automáticamente el estado

Consulte github.com/mcmlxxxviii/react-value-link

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top