import React from "react";
import ReactDOM from "react-dom";
class Counter extends React.Component {
constructor(props) {
super(props);
this.num1 = React.createRef(); //创建ref对象,挂到当前组件上
this.num2 = React.createRef();
this.res = React.createRef();
this.state = {
num1: 0,
num2: 0
};
}
handleChange(e) {
console.log(e.target.dataset.name);
this.setState({
[e.target.dataset.name]:parseFloat(e.target.value)
});
}
render() {
return (
<div>
<input type ="number" data-name="num1" ref={this.num1} value={this.state.num1} onChange={this.handleChange.bind(this)} /> +
<input type ="number" data-name="num2" ref={this.num2} value={this.state.num2} onChange={this.handleChange.bind(this)} />
<button>=</button>
<input type ="number" ref={this.res} value={this.state.num1 + this.state.num2} readOnly />
</div>
);
}
}
ReactDOM.render(<Counter />, window.app);