react 字符串形式的ref,不建议使用

geekymv 发表于:2024-08-25 12:31:16 阅读数:811

字符串形式的ref

<div id="test"></div>

        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <!-- 引入 rop-types.js 用于对属性标签属性进行限制 -->
        <script src="https://unpkg.com/[email protected]/prop-types.js"></script>

        <!-- 引入 babel, 用于将 jsx 转为 js -->
        <!-- Don't use this in production: -->
        <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

        <!-- 此处一定要写 babel -->
        <script type="text/babel">
            
            /*
            字符串形式的ref
            */
            class Demo extends React.Component {

                showData = ()=> {
                    // console.log('showData:', this)
                    const {input1} = this.refs
                    alert(input1.value)
                }

                showData2 = ()=> {
                    const {input2} = this.refs
                    alert(input2.value)
                }

                render() {
                    return (
                        <div>
                            <input ref="input1" type="text" placeholder="点击按钮提示数据" />
                            <button onClick={this.showData}>点我提示左侧的数据</button>
                            <input ref="input2" onBlur={this.showData2} type="text" palceholder="失去焦点提示数据" />
                        </div>
                    )
                }

            }

            ReactDOM.render(<Demo/>, document.getElementById('test'))

        </script>

Barbara Middleton
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis porta eros lacus, nec ultricies elit blandit non. Suspendisse pellentesque mauris sit amet dolor blandit rutrum. Nunc in tempus turpis.
Like · Reply · 3 hrs

Sean Brown
Donec sollicitudin urna eget eros malesuada sagittis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam blandit nisl a nulla sagittis, a lobortis leo feugiat.
Like · Reply · 2 hrs

Vivamus quis semper metus, non tincidunt dolor. Vivamus in mi eu lorem cursus ullamcorper sit amet nec massa.
Morbi vitae diam et purus tincidunt porttitor vel vitae augue. Praesent malesuada metus sed pharetra euismod. Cras tellus odio, tincidunt iaculis diam non, porta aliquet tortor.

Kayli Eunice
Sed convallis scelerisque mauris, non pulvinar nunc mattis vel. Maecenas varius felis sit amet magna vestibulum euismod malesuada cursus libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus lacinia non nisl id feugiat.
Like · Reply · 2 hrs