0

estoy haciendo una practica en react soy principiante y tengo esta incógnita, en esta practica tengo unos inputs que se renderizan de manera dinamica por un map, como haría para que cada dato de cada uno de los inputs renderizados se guarde en un state diferente. este es mi código hasta los momentos, gracias de antemano.

export class RenderizadoPrueba extends Component{

  constructor(props){
    super(props);
    this.state ={
      values: '',
      nroRenderElemento: 3,
      inputs: []
    }
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e){
    this.setState({
        value: e.target.value
    });
  }

  handleSubmit(e){
    console.log('Este es el nombre introducido:', this.state.value);
    e.preventDefault();
  }

  componentDidMount(){
    this.setState({
      inputs: [... Array(this.state.nroRenderElemento)].map((input, i) =>
        <label key={input}>
          Introduzca su Nombre:
          <input type="text" name={i} onChange={this.handleChange}/>
        </label>
      )
    })
  }

  render(){
    return(
      <div> 
        <form onSubmit={this.handleSubmit}>
          {this.state.inputs}
          <input type="submit" value="Submit"/>
        </form>
      </div>
    )
  }
}

1 respuesta 1

2

Acá te dejo como quedaría, algunas cosas a tener en cuenta

  • Los valores los estoy guardando en un array, con el mismo index que el del input.
  • Usé el metodo slice en el array de values para hacer un shallow copy del array y para no mutarlo. Lo modifico y luego lo reemplazo por el anterior.
  • También cambié la llamada del callback onChange creando una funcion anonima para poder pasarle un parametro extra que es el index.

class RenderizadoPrueba extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      values: [],
      nroRenderElemento: 3,
      inputs: []
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e, index) {
    const values = this.state.values.slice();
    values[index] = e.target.value;
    this.setState({values});
    console.log(this.state);
  }

  handleSubmit(e) {
    console.log("Este es el nombre introducido:", this.state.value);
    e.preventDefault();
  }

  componentDidMount() {
    this.setState({
      inputs: [...Array(this.state.nroRenderElemento)].map((input, i) => (
        <label key={input}>
          Introduzca su Nombre:
          <input type="text" name={i} onChange={e => this.handleChange(e, i)} />
        </label>
      ))
    });
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          {this.state.inputs}
          <input type="submit" value="Submit" />
        </form>
      </div>
    );
  }
}

ReactDOM.render(<RenderizadoPrueba />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

1
  • Muchas Gracias, :D
    – FGutierrez
    el 26 sep. 2019 a las 18:33

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.