Skip to content

React.forwardRef的使用

司徒正美 edited this page Jul 19, 2019 · 1 revision
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
<!--

 <script src="https://cdn.bootcss.com/react/16.7.0-alpha.2/umd/react.development.js"></script>
 <script src="https://cdn.bootcss.com/react-dom/16.7.0-alpha.2/umd/react-dom.development.js"></script>
  <script src="./lib/ReactPropTypes.js"></script>
-->

<script src="./dist/React.js"></script>

  <script type='text/javascript' src="./lib/babel.js"></script>

</head>

<body>

  <div id='root' class="root">

  </div>
  <script type='text/babel'>

const MyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="MyButton">
    {props.children}
  </button>
));

// 通过ref可以直接操作<button>元素:
const ref = React.createRef();

var a = null
 ReactDOM.render( <MyButton ref={ref} a="1" >Click me!</MyButton>, document.getElementById('root'),function(){
   console.log(ref, this)
 });
	
    </script>
  </body>
</html>