我有这两个组成部分:
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
它记录在此页面上的示例中:
https://reactjs.org/docs/refs-and-the-dom.html
为了安全起见,我也尝试了js小提琴,它按预期工作! https://jsfiddle.net/n5u2wwjg/195724/
如果你想获得React组件的DOM节点,我认为处理这个问题的首选方法是让子组件完成繁重的工作.因此,如果您想要将焦点调用到组件内部的输入,例如,您将获得组件来设置ref并在组件上调用方法,例如
this.myComponentRef.focusInput()
然后componentRef将有一个名为focusInput的方法,然后调用焦点在输入上.
如果您不想这样做,那么您可以使用findDOMNode进行攻击,我想这就是为什么不鼓励它!
(编辑,因为我在回答之后意识到你已经知道了当前并想知道反应组件.超级抱歉!)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。