react 组件ref属性

时间:2020-05-01
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</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 src="js/prop-types.js"></script>

<script type="text/babel">
    // 创建组件
    class InputComponent extends React.Component{
        constructor(props) {
            super(props);

            this.handleClick = this.handleClick.bind(this);
        }

        handleClick(){
            let content = this.refs.content.value;
            alert(content);
        }

        render() {
            return (
                <div>
                    <input type="text" ref="content"/>
                    <button onClick={this.handleClick}>点击获取输入框中的数据</button>
                </div>
            );
        }
    }

    // 渲染虚拟dom
    ReactDOM.render(<InputComponent/>,document.getElementById('test'));
</script>
</body>
</html>