React中的三大实例之ref的三种形式

React中实例的三大属性之 ref

ref 有三种形式:

  1. 字符串形式
  2. 回调函数形式
  3. 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)
      }

      /*
        React.createRef() 调用后可以返回一个容器,该容器
        可以存储被ref所标识的结点,但是该节点是专人专用只能存放一个标签
      */
      myRef = React.createRef()
      // 展示第三个输入框的内容
      showData3 = () => {
     
     
        alert(this.myRef.current.value)
      }

      render() {
     
     
        return (
          <div>
            {
     
     /* 1.字符串形式的ref */}
            <input ref="input1" type="text" placeholder="点击按钮提示数据" />
            <button onClick={
     
     this.showData1}>点我提示第一个输入框中的内容</button><br /><br />

            {
     
     /* 2.回调函数形式的ref */}
            <input ref={
     
     (c) => {
     
      this.input2 = c }} type="text" placeholder="点击按钮提示数据" />
            <button onClick={
     
     this.showData2}>点我提示第二个输入框中的内容</button><br /><br />

            {
     
     /* 3.createRef的ref */}
            <input ref={
     
     this.myRef} type="text" placeholder="点击按钮提示数据" />
            <button onClick={
     
     this.showData3}>点我提示第三个输入框中的内容</button>
          </div>
        )
      }
    }
    // 渲染组件页面
    ReactDOM.render(<Demo />, document.getElementById('test'))
  </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/qq_49002903/article/details/115911988