react入门-refs

vue有ref来获取template里面的子组件/子元素,react当然也有:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
    <script src="common/react.js"></script>
    <script src="common/react-dom.js"></script>
    <script src="https://cdn.bootcss.com/babel-core/5.8.38/browser.js"></script>
    <script type="text/babel">
        class App extends React.Component {
            constructor(opts) {
                super(opts)
                this.focus = this.focus.bind(this)
            }
            focus() {
                //this.refs.amie获取的是原生的"<input ref="amie" type="text" />"DOM
                this.refs.amie.focus()
            }
            render() {
                return <div>
                    <input ref="amie" type="text" />
                    <input type="button" value="focus" onClick={this.focus}/>
                </div>
            }
        }
        ReactDOM.render(
            <App />,
            document.getElementById('app')
        )
    </script>
</body>
</html>

 

posted @ 2018-03-04 20:10  张啊咩  阅读(935)  评论(0编辑  收藏  举报