[英]React.js passing => in props
Follow up on this question but deserved a separate thread Trying to convert React.CreateClass to extends React.Component . 跟进此问题,但应使用单独的线程尝试将React.CreateClass转换为扩展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: 我想知道如何在调用组件时使用=>,但又不传入确切的输入名称,而是应该在内部填充组件:
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: 以下将起作用,但仅适用于
username
段:
<FormFields unamepwd={this.state}
handleChange={() => self.handleChange('username')} updateChanges={self.updateToServer} />
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')
You can use e.target
in the function handling onChange event to get a reference to the input that has triggered the event. 您可以在处理onChange事件的函数中使用
e.target
来获取对触发该事件的输入的引用。 So you only pass a reference to the handleChange
function arround, no need for {x => handleChange('name') }
or { handleChange.bind('name') }
or whatever. 因此,您只需传递对
handleChange
函数handleChange
的引用,就不需要{x => handleChange('name') }
或{ handleChange.bind('name') }
或其他任何东西。
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 } />
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.