React从入门到精通系列之(14)refs和DOM元素
十四、refs和DOM元素在典型的React数据流中,props是父组件与其子组件交互的唯一方式。 要修改子组件,需要使用一个新的props进行重新渲染。 但是,在某些情况下,您需要在典型数据流之外强制修改子组件。 要修改的子组件可以是React组件实例,也可以是DOM元素。 对于这两种情况,React提供了一个以下这样的功能。 通过ref属性设置回调函数React提供可以附加到任何组件的特殊属性。 当在HTML元素上使用 import React from 'react'; import ReactDOM from 'react-dom'; class CustomTextInput extends React.Component { constructor(props) { super(props); this.focus = this.focus.bind(this); } focus() { // textInput是一个标准的DOM元素 this.textInput.focus(); } render() { return ( <div> <input type="text" ref={input => { this.textInput = input; }}/> <input type="button" value="选中上面的text input" onClick={this.focus}/> </div> ); } } ReactDOM.render( <CustomTextInput/>,document.getElementById('root') ); 当组件装载(mounting)时,React将使用DOM元素调用 使用 当在自定义组件上使用 class AutoFocusTextInput extends React.Component { componentDidMount() { this.textInput.focus(); } render() { return ( <CustomTextInput ref={input => {this.textInput = input; }} /> ); } } 您不能在功能性组件上使用 function CustomTextInput(props) { // 这里必须提前顶一个textInput,只有这样才可以正常执行ref回调函数 let textInput = null; function click() { textInput.focus(); } return ( <div> <input type="text" ref={input => { textInput = input; }} /> <input type="button" value="选中这个输入框" onClick={this.click} /> </div> ); } 不要过度使用ref你的第一个倾向可能是使用 如果是这种情况,你必须花一点时间,关键去考虑在组件层次结构中应该拥有什么状态。通常,在层次结构中处于更高级别的组件“拥有”状态是一个让一切便清除的最适当位置。 有关示例,请参阅本系列的第10篇《提升state》。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |