React.js passing => in props

2019-07-27 01:15发布

问题:

Follow up on this question but deserved a separate thread Trying to convert React.CreateClass to extends React.Component.

I'm wondering how I can make use of => while calling the component but without passing in the exact input name, that should get filled up by the component internally:

Component:

var FormFields = React.createClass({
    render: function() {
        const upwd = this.props.unamepwd;
        return(
        <form>
            Username: <input value={upwd.username} 
              onChange={this.props.handleChange('username')} /><br />
            Password: <input type="password" value={upwd.password} 
              onChange={this.props.handleChange('password')} />
          <button onClick={this.props.updateChanges}>Go!</button>
        </form>
        );
    }
});

While in the parent render method I would like to call it something like:

<FormFields unamepwd={this.state} 
    handleChange={() => self.handleChange()} updateChanges={self.updateToServer} />

The following would work but only for the username field:

<FormFields unamepwd={this.state} 
  handleChange={() => self.handleChange('username')} updateChanges={self.updateToServer} />

回答1:

Just pass an argument to the function.

<FormFields unamepwd={this.state} 
    handleChange={(fieldName) => self.handleChange(fieldName)} updateChanges={self.updateToServer} />

and call it like:

this.props.handleChange('password') 


回答2:

You can use e.target in the function handling onChange event to get a reference to the input that has triggered the event. So you only pass a reference to the handleChange function arround, no need for {x => handleChange('name') } or { handleChange.bind('name') } or whatever.

var FormFields = React.createClass({
    render: function() {
        const upwd = this.props.unamepwd;
        return(
            <form>
              Username: <input value={upwd.username} 
                               onChange={this.props.handleChange} name="username" /><br />
              Password: <input type="password" value={upwd.password} 
                               onChange={this.props.handleChange} name="password" />
              <button onClick={this.props.updateChanges}>Go!</button>
            </form>
        );
    }
});

var Parent = React.createClass({
    handleChange(e){
        console.log( e.target.name );
    },
    render(){
        return <FormFields handleChange={ this.handleChange }  />
    }
});

http://jsfiddle.net/mg5cbepk/