reactjs – 如何使用React.createRef()API从类组件ref获取DOM节
我有这两个组成部分:
import { findDOMNode } from 'react-dom'; class Items extends Component { constructor(props) { super(props); this.ref = React.createRef(); this.selectedItemRef = React.createRef(); } componentDidMount() { if (this.props.selectedItem) { this.scrollToItem(); } } componentWillReceiveProps(nextProps) { if (this.props.selectedItem !== nextProps.selectedItem) { this.scrollToItem(); } } scrollToItem() { const itemsRef = this.ref.current; const itemRef = findDOMNode(this.selectedItemRef.current); // Do scroll stuff here } render() { return ( <div ref={this.ref}> {this.props.items.map((item,index) => { const itemProps = { onClick: () => this.props.setSelectedItem(item.id) }; if (item.id === this.props.selectedItem) { itemProps.ref = this.selectedItemRef; } return <Item {...itemProps} />; })} </div> ); } } Items.propTypes = { items: PropTypes.array,selectedItem: PropTypes.number,setSelectedItem: PropTypes.func }; 和 class Item extends Component { render() { return ( <div onClick={() => this.props.onClick()}>item</div> ); } } Item.propTypes = { onClick: PropTypes.func }; 在Items :: scrollToItem()中获取this.selectedItemRef的DOM节点的正确方法是什么? React docs不鼓励使用findDOMNode(),但还有其他方法吗?我应该在Item中创建ref吗?如果是这样,我如何访问Items :: componentDidMount()中的ref? 谢谢
我想你想要的是最新的,例如this.selectedItemRef.current
它记录在此页面上的示例中: 为了安全起见,我也尝试了js小提琴,它按预期工作! https://jsfiddle.net/n5u2wwjg/195724/ 如果你想获得React组件的DOM节点,我认为处理这个问题的首选方法是让子组件完成繁重的工作.因此,如果您想要将焦点调用到组件内部的输入,例如,您将获得组件来设置ref并在组件上调用方法,例如 this.myComponentRef.focusInput() 然后componentRef将有一个名为focusInput的方法,然后调用焦点在输入上. 如果您不想这样做,那么您可以使用findDOMNode进行攻击,我想这就是为什么不鼓励它! (编辑,因为我在回答之后意识到你已经知道了当前并想知道反应组件.超级抱歉!) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |