React事件处理函数的bind复用和name复用

时间:2021-01-07 21:03:32

一、bind复用

 <!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>表单详解</title>
</head>
<body>
<script src="./react-0.13.2/react-0.13.2/build/react-with-addons.js"></script>
<script src="./react-0.13.2/react-0.13.2/build/JSXTransformer.js"></script>
<script type="text/jsx">
var MyForm = React.createClass({
getInitialState: function () {
return {
username: "",
gender: "man",
checked: true
};
},
handleChange: function (name, event) {
var newState = {};
newState[name] = name == "checked" ? event.target.checked : event.target.value;
this.setState(newState);
},
submitHandler: function (event) {
event.preventDefault();
console.log(this.state);
},
render: function () {
return <form onSubmit={this.submitHandler}>
<label htmlFor="username">请输入用户名:</label>
<input id="username" type="text" value={this.state.username} onChange={this.handleChange.bind(this, "username")} />
<br />
<select value={this.state.gender} onChange={this.handleChange.bind(this, "gender")}>
<option value="man">男</option>
<option value="woman">女</option>
</select>
<br />
<label htmlFor="checkbox">同意用户协议</label>
<input id="checkbox" type="checkbox" value="agree" checked={this.state.checked} onChange={this.handleChange.bind(this, "checked")} />
<button type="submit">注册</button>
</form>;
}
});
React.render(<MyForm></MyForm>, document.body);
</script>
</body>
</html>

二、name复用

 <!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>表单详解</title>
</head>
<body>
<script src="./react-0.13.2/react-0.13.2/build/react-with-addons.js"></script>
<script src="./react-0.13.2/react-0.13.2/build/JSXTransformer.js"></script>
<script type="text/jsx">
var MyForm = React.createClass({
getInitialState: function () {
return {
username: "",
gender: "man",
checked: true
};
},
handleChange: function (event) {
var newState = {};
newState[event.target.name] = event.target.name == "checked" ? event.target.checked : event.target.value;
this.setState(newState);
},
submitHandler: function (event) {
event.preventDefault();
console.log(this.state);
},
render: function () {
return <form onSubmit={this.submitHandler}>
<label htmlFor="username">请输入用户名:</label>
<input name="username" id="username" type="text" value={this.state.username} onChange={this.handleChange} />
<br />
<select name="gender" value={this.state.gender} onChange={this.handleChange}>
<option value="man">男</option>
<option value="woman">女</option>
</select>
<br />
<label htmlFor="checkbox">同意用户协议</label>
<input id="checkbox" name="checked" type="checkbox" value="agree" checked={this.state.checked} onChange={this.handleChange} />
<button type="submit">注册</button>
</form>;
}
});
React.render(<MyForm></MyForm>, document.body);
</script>
</body>
</html>