我想知道这是否是一种好的做法,或者我是否应该以不同的方式设计这个应用程序。我特别关心这两个“handleChange”函数,想知道是否可以通过某种方式对其进行简化。当然,我们也欢迎其他建议。
用户添加.js:
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {createUser} from '../actions/index'
class UserCreate extends Component {
constructor(props, context) {
super(props, context);
this.state = {
inputText: 'Helluuuu'
}
}
handleChangeFirstName(event) {
console.log(event.target.value);
this.setState({
inputTextFirstName: event.target.value
})
}
handleChangeLastName(event) {
console.log(event.target.value);
this.setState({
inputTextLastName: event.target.value
})
}
render() {
return (
<div>
<h2> Add User </h2>
<table className="userTable">
<tbody>
<tr>
<td>First Name:</td>
<td>Last Name:</td>
</tr>
<tr>
<td>
<input type="text"
placeholder="Hello!"
value={this.state.inputTextFirstName}
onChange={this.handleChangeFirstName.bind(this)}/>
</td>
<td>
<input type="text"
placeholder="Hello!"
value={this.state.inputTextLastName}
onChange={this.handleChangeLastName.bind(this)} />
</td>
</tr>
</tbody>
</table>
<button onClick={() =>this.props.createUser()}>Submit</button>
</div>
);
}
}
function mapStateToProps(state) {
return {
user: state.activeUser
};
}
function matchDispatchToProps(dispatch){
return bindActionCreators({createUser: createUser}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(UserCreate);
最佳答案
当然,您可以将其减少到只有一个 handleChange
方法,并且可以使用该方法使用任意数量的输入字段。
此外,我认为您不需要为此使用任何第三方软件包。
在你的渲染方法中:
<input
type="text"
name="firstName"
placeholder="First Name!"
value={this.state.firstName}
onChange={this.handleChange.bind(this)}
/>
<input
type="text"
name="lastName"
placeholder="Last Name!"
value={this.state.lastName}
onChange={this.handleChange.bind(this)}
/>
处理更改方法
handleChange(e) {
this.setState({ [e.target.name] : e.target.value });
}
更干净。
关于javascript - 组件中每个元素的不同 handleChange() 函数? ( react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40302344/