1.定义:组件内的标签可以定义ref属性来标识自己。
2.使用ref的三种方法
- 字符串形式的ref (这个写法会慢慢替换掉,所以尽量不要写字符串形式)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>1_字符串形式的ref</title>
</head>
<body>
<div id="text"></div>
<script src="../../js/react.development.js"></script>
<script src="../../js/react-dom.development.js"></script>
<script src="../../js/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component{
// 左侧
left = ()=>{
const input = this.refs.input1
alert(input.value)
console.log(this.refs.input1)
}
// 右侧
right = ()=>{
const input = this.refs.input2
alert(input.value)
}
render(){
return (
<div>
<input ref="input1" type="text" placeholder="点击确定弹框" />
<button onClick={this.left}>确定</button>
<input ref="input2" onBlur={this.right} type="text" placeholder="失去焦点弹框" />
</div>
)
}
}
ReactDOM.render(<Demo />,document.getElementById('text'))
</script>
</body>
</html>
- 回调形式的ref(主推用这个形式写)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2_回调形式的ref</title>
</head>
<body>
<div id="text"></div>
<script src="../../js/react.development.js"></script>
<script src="../../js/react-dom.development.js"></script>
<script src="../../js/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component{
// 左侧
left = ()=>{
console.log('@',this)
const input = this.input1
alert(input.value)
console.log(this)
}
// 右侧
right = ()=>{
const input = this.input2
alert(input.value)
}
render(){
return (
<div>
<input ref={(c)=>{this.input1 = c}} type="text" placeholder="点击确定弹框" />
<button onClick={this.left}>确定</button>
<input ref={(c)=>{this.input2 = c}} onBlur={this.right} type="text" placeholder="失去焦点弹框" />
</div>
)
}
}
ReactDOM.render(<Demo />,document.getElementById('text'))
</script>
</body>
</html>
-
createRef 创建 ref 容器(这个相对来说比较麻烦一些
html<div id="text"></div> <script src="../../js/react.development.js"></script> <script src="../../js/react-dom.development.js"></script> <script src="../../js/babel.min.js"></script> <script type="text/babel"> class Login extends React.Component { createRef1= React.createRef() createRef2= React.createRef() left= ()=>{ const input = this.createRef1 alter(input.value) } left= ()=>{ const input = this.createRef2 alter(input.value) } render(){ //这样写是把username和password 放在了login中,如果还是很迷糊不知道在那的话,可以在left函数中输出this return ( <div> <input ref={this.createRef1} type="text" placeholder="点击确定弹框" /> <button onClick={this.left}>确定</button> <input ref={this.createRef2} onBlur={this.right} type="text" placeholder="失去焦点弹框" /> </div> ) } } ReactDOM.render(<Login />,document.getElementById('text')) </script>