Pregunta

Tengo este código ReactJS para mostrar un botón de imagen personalizado que alterna entre 2 imágenes diferentes para el estado ENCENDIDO y APAGADO.¿Existe una forma más sencilla de hacer esto?Esperaba que CSS contuviera menos líneas de código, pero no pude encontrar un ejemplo simple.

El siguiente código pasa el estado desde <MyIconButton> a <MyPartyCatButton> luego a <MyHomeView>.Mi aplicación tendrá 4 de estos botones personalizados en la pantalla de inicio, por eso lo descarté <MyIconButton>.

Por cierto, esto es para una aplicación móvil y leí (y lo noté yo mismo) que es muy lento usar casillas de verificación en los navegadores móviles;Por eso elegí probar esto sin usar casillas de verificación.

código reaccionarjs

var MyIconButton = React.createClass({

  handleSubmit: function(e) {
    e.preventDefault();
    console.log("INSIDE: MyIconButton handleSubmit");

    // Change button's state ON/OFF, 
    // then sends state up the food chain via            
    //  this.props.updateFilter( b_buttonOn ).
    var b_buttonOn = false;
    if (this.props.pressed === true) {
      b_buttonOn = false;
    }
    else {
      b_buttonOn = true;
    }
    // updateFilter is a 'pointer' to a method in the calling React component.
    this.props.updateFilter( b_buttonOn ); 
  },

  render: function() {

    // Show On or Off image.
    // ** I could use ? : inside the JSX/HTML but prefer long form to make it explicitly obvious. 
    var buttonImg = "";
    if (this.props.pressed === true) {
      buttonImg = this.props.onpic;
    }
    else {
      buttonImg = this.props.offpic;
    }

    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input type="image" src={buttonImg}></input>
        </form>
      </div>
    );
  }
});


// <MyPartyCatButton> Doesn't have it's own state, 
// passes state of <MyIconButton> 
// straight through to <MyHomeView>.
var MyPartyCatButton = React.createClass({

  render: function() {
    return (
      <MyIconButton pressed={this.props.pressed} updateFilter={this.props.updateFilter} onpic="static/images/icon1.jpeg" offpic="static/images/off-icon.jpg"/>
    );
  }
});

//
// Main App view
var MyHomeView = React.createClass({
  getInitialState: function() {
    // This is where I'll eventually get data from the server.
    return {
      b_MyPartyCat: true
    };
  },

  updatePartyCategory: function(value) {
    // Eventually will write value to the server.
    this.setState( {b_MyPartyCat: value} );
    console.log("INSIDE: MyHomeView() updatePartyCategory() " + this.state.b_MyPartyCat );
  },

  render: function() {
    return (
        <div>
         <MyPartyCatButton pressed={this.state.b_MyPartyCat} updateFilter={this.updatePartyCategory}/>
        </div>

        // Eventually will have 3 other categories i.e. Books, Skateboards, Trees !
    );
  }
});
¿Fue útil?

Solución

si actualiza dinámicamente el componente 'presionado' del componente (como lo hizo), simplemente

var MyIconButton= React.createClass({
    render: function(){
        var pic= this.props.pressed? this.props.onpic : this.props.offpic
        return <img 
            src={pic} 
            onClick={this.props.tuggleSelection}  //updateFilter is wierd name
        />
    }
})

(EDITAR:De esta manera, en el componente MyPartyCatButton, puede pasar la función para manejar el evento 'tuggleSelection'.El argumento de la función de evento es un objeto de evento, pero ya tienes el estado del botón en el estado contenedor (el anterior, por lo que debes invertirlo).tu código será algo así:

render: function(){
    return <MyIconButton pressed={this.state.PartyCatPressed} tuggleSelection={this.updatePartyCategory} />
}
updatePartyCategory: function(e){
    this.setState( 
        {PartyCatPressed: !this.state.PartyCatPressed} //this invert PartyCatPressed value
    );
    console.log("INSIDE: MyHomeView() updatePartyCategory() " + this.state.b_MyPartyCat )
}

)

pero si no lo hace, use prop para el valor predeterminado:

var MyIconButton= React.createClass({
    getInitialState: function(){
        return {pressed: this.props.defultPressed}
    },
    handleClick: function(){
        this.setState({pressed: !this.state.pressed})
    },

    render: function(){
        var pic= this.state.pressed? this.props.onpic : this.props.offpic
        return <img 
            src={pic} 
            onClick={this.handleClick}
        />
    }
})
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top