v2 tree 获取不到 this.refs.tree
时间: 2024-05-13 17:18:19 浏览: 13
`this.refs.tree` 是 React 中引用 DOM 元素的老方式,它已被弃用。现在应该使用 `React.createRef()` 来创建一个 ref,并通过 `ref.current` 来引用 DOM 元素。
在 v2 版本的 `react-sortable-tree` 中,你可以这样使用 ref:
```jsx
import SortableTree from 'react-sortable-tree';
class MyTree extends React.Component {
constructor(props) {
super(props);
this.treeRef = React.createRef();
}
render() {
return (
<div>
<SortableTree
treeData={myTreeData}
onChange={this.props.onChange}
ref={this.treeRef}
/>
<button onClick={() => console.log(this.treeRef.current)}>Log Tree</button>
</div>
);
}
}
```
在上面的代码中,我们创建了一个 `treeRef` ref,并将其传递给 `react-sortable-tree` 的 `ref` 属性。然后,我们可以在组件中的其他地方,使用 `this.treeRef.current` 来引用 DOM 元素。在这个例子中,我们将 `treeRef.current` 打印到控制台中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)