React中我们可以使用Refs来访问 DOM 节点
使用方式:
方式一(推荐)
class Add extends React.Component {
constructor(props) {
super(props)
this.num1 = React.createRef();
this.num2 = React.createRef();
this.result = React.createRef();
}
add = ()=>{
let num1 = this.num1.current;
let num2 = this.num2.current;
let result = this.result.current;
result.value = parseFloat(num1.value) + parseFloat(num2.value);
}
render(){
return (
<>
<input ref={ this.num1 } />
<input ref={ this.num2 } />
<button onClick={ this.add }>=</button>
<input ref={ this.result } />
</>
)
}
}
方式二
class Add extends React.Component {
add = ()=>{
let num1 = this.num1;
let num2 = this.num2;
let result = this.result;
result.value = parseFloat(num1.value) + parseFloat(num2.value);
}
render(){
return (
<>
<input ref={ el => this.num1 = el } />
<input ref={ el => this.num2 = el } />
<button onClick={ this.add }>=</button>
<input ref={ el => this.result = el } />
</>
)
}
}
方式三(即将删除,不建议使用)
class Add extends React.Component {
add = ()=>{
let num1 = this.refs.num1;
let num2 = this.refs.num2;
let result = this.refs.result;
result.value = parseFloat(num1.value) + parseFloat(num2.value);
}
render(){
return (
<>
<input ref="num1" />
<input ref="num2" />
<button onClick={ this.add }>=</button>
<input ref="result" />
</>
)
}
}