How can I pass two arguments with props in React?

0

Hi, I'm new in this React but I have a question with the parameters, I just want to print the name and age as soon as the input changes state, when entering the age in the second input modify the name And not age, why does this happen to me? Or how can I add the second parameter to Header .

I'd like something like this:

class Mensaje extends React.Component {
  constructor (props) {
  super(props);
  this.state = {name: ''}; this.state = {edad:''};
  this.cambioNombre = this.cambioNombre.bind(this);
  this.cambioEdad = this.cambioEdad.bind(this);
  }
  cambioNombre(name) {this.setState({name}); }
  cambioEdad(edad) {this.setState({edad}); }
    render () { return ( <div>
        <Header name={this.state.name} />
       <Input cambioNombre={this.cambioNombre} cambioEdad={this.cambioEdad}/>
   </div> );
  }
}
const Header = (props) => {
  return(
    <div className="hi">
      <h3>Hello, {props.name || "visitor"}, tu edad es {props.edad || "100 años"}!</h3>
    </div>
  );   
}
class Input extends React.Component {
    constructor() {super(); this.state = {input:''} }
  nombreChange(e) {const name = e.target.value;
    this.setState({input:name});
    this.props.cambioNombre(name); }


  render() {
    return(<div>

      <input placeholder='introduce tu nombre' type='text'
      name={this.state.name} onChange={this.nombreChange.bind(this)}>
      </input>
      <br></br>
      <input placeholder='introduce tu edad' type='text'
      name={this.state.name} onChange={this.nombreChange.bind(this)}>
      </input>

    </div>);
  }
}
    
asked by Gerardo Bautista 22.12.2017 в 22:12
source

1 answer

1

In the Message component you are defining 2 times state! And you're also not aging the Header.

This would be more valid:

constructor (props) {
  super(props);
  this.state = {
    name: '', 
    edad: ''
  };

  this.cambioNombre = this.cambioNombre.bind(this);
  this.cambioEdad = this.cambioEdad.bind(this);
}

render() { 
  return (
    <div>
      <Header name={this.state.name} edad={this.state.edad} />
      <Input cambioNombre={this.cambioNombre} cambioEdad={this.cambioEdad}/>
    </div> 
  );
}

Or you directly pass the whole object state to the child

<Header info={this.state} />
    
answered by 24.10.2018 / 16:44
source