关于 React Refs
发布时间:2020-12-15 09:33:29 所属栏目:百科 来源:网络整理
导读:一、什么是 ref React 提供了 ref 属性,用来对元素进行 DOM 操作 ? ? 二、使用 ref 的方式 ? 1、字符串模式 绑定 ref 属性 XX,通过 this.refs.XX 获取 class refTest extends React.Component { constructor(props) { super (props); this .state = { } }
一、什么是 refReact 提供了 ref 属性,用来对元素进行 DOM 操作 ? ? 二、使用 ref 的方式? 1、字符串模式绑定 ref 属性 XX,通过 this.refs.XX 获取 class refTest extends React.Component { constructor(props) { super(props); this.state = { } } handleClick() { console.log(this.refs.inputElem.value) } render() { return ( <React.Fragment> <div> <input type="text" ref="inputElem" /> </div> <button onClick={this.handleClick.bind(this)}>toConsole</button> </React.Fragment> ) } } 字符串模式不支持静态类型检测,且 React 不建议使用 ? 2、回调函数模式在 ref 属性中设置回调函数,通过 this.XX 获取 class refTest extends React.Component { constructor(props) { super(props); this.state = { } } handleClick() { console.log(this.inputElem.value) } render() { return ( <React.Fragment> <div> <input type="text" ref={(input) => this.inputElem = input} /> </div> <button onClick={this.handleClick.bind(this)}>toConsole</button> </React.Fragment> ) } } 运行结果: 点击“toConsole”在控制台输出:? 回调函数模式支持静态类型检测 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |