第一种 字符串的ref
ref=“myRef” 里面的绑定是字符串的绑定用法,这种ref的形式写多了影响效率问题,官方文档已经不推荐此写法
//创建类式组件
class Demo extends React.Component {
//点击按钮
showData = () => {
const { input1 } = this.refs;
alert(input1.value);
};
showData2 = () => {
const { input2 } = this.refs;
alert(input2.value);
};
render() {
return (
<div>
<input type="text" ref="input1" placeholder="点击按钮提示数据" />
<button onClick={this.showData}>点我提示左侧的数据</button>
<input
type="text"
ref="input2"
onBlur={this.showData2}
placeholder="失去焦点提示数据"
/>
</div>
);
}
}
第二种 回调形式的ref的用法
//创建类式组件
class Demo extends React.Component {
//点击按钮
showData = () => {
const { input1 } = this;
alert(input1.value);
};
showData2 = () => {
const { input2 } = this;
alert(input2.value);
};
render() {
return (
<div>
<input
type="text"
ref={(c) => (this.input1 = c)}
placeholder="点击按钮提示数据"
/>
<button onClick={this.showData}>点我提示左侧的数据</button>
<input
type="text"
ref={(c) => (this.input2 = c)}
onBlur={this.showData2}
placeholder="失去焦点提示数据"
/>
</div>
);
}
}
**这种回调形式的写法也发现了问题 就是调用次数比较多
在点击更新组件的时候:
首先render函数先将原来的回调清空,赋值为null,然后才重新渲染 所以出现两次执行情况**
虽然不影响使用,单如果想要达到最优的效果可以稍微改进一下写法:
//创建类式组件
class Demo extends React.Component {
//点击按钮
showData = () => {
const { input1 } = this;
alert(input1.value);
};
showData2 = () => {
const { input2 } = this;
alert(input2.value);
};
//回调形式的ref
input2 = (c) => (this.input2 = c);
render() {
return (
<div>
<input
type="text"
ref={(c) => (this.input1 = c)}
placeholder="点击按钮提示数据"
/>
<button onClick={this.showData}>点我提示左侧的数据</button>
<input
type="text"
// {ref={(c) => (this.input2 = c)}} 这种方式的话每次渲染都得重新生在更新的时候出现c返回null情况 虽然不影响使用 但也可以使用以下这种方式改进
ref={this.input2}
onBlur={this.showData2}
placeholder="失去焦点提示数据"
/>
</div>
);
}
}
第三种 API(React.createdRef())容器的ref的用法— 目前是官方推荐使用最新的方式
export default class App extends Component {
myRef = React.createRef()
//点击获取inut的数据
showData = () => {
console.log(this.myRef.current.value)
}
render() {
return <div >
< input type = "text" ref = {this.myRef}/>
<button onClick = {this.showData} > 点击显示输入框的数据 < /button> < /div >
}
}