React中实例的三大属性之 ref
ref 有三种形式:
- 字符串形式
- 回调函数形式
CreateRef
形式
如下示例代码展示了三种形式ref
的创建于使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>三种方式的ref</title>
</head>
<body>
<div id="test"></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 {
showData1 = () => {
const { input1 } = this.refs
alert(input1.value)
}
showData2 = () => {
const { input2 } = this
alert(input2.value)
}
myRef = React.createRef()
showData3 = () => {
alert(this.myRef.current.value)
}
render() {
return (
<div>
{}
<input ref="input1" type="text" placeholder="点击按钮提示数据" />
<button onClick={this.showData1}>点我提示第一个输入框中的内容</button><br /><br />
{}
<input ref={(c) => { this.input2 = c }} type="text" placeholder="点击按钮提示数据" />
<button onClick={this.showData2}>点我提示第二个输入框中的内容</button><br /><br />
{}
<input ref={this.myRef} type="text" placeholder="点击按钮提示数据" />
<button onClick={this.showData3}>点我提示第三个输入框中的内容</button>
</div>
)
}
}
ReactDOM.render(<Demo />, document.getElementById('test'))
</script>
</body>
</html>