我想创建一个呈现SVG路径元素的组件:
class Path extends Component {
constructor(props) {
super(props);
this.refCallback = this.refCallback.bind(this);
}
refCallback(element) {
console.log("Element: ", element, element.getTotalLength());
}
render() {
const { data, id } = this.props
return (
<path d={ data } id={ id } ref={ this.refCallback } />
);
}
}
我希望获得路径的DOM节点,然后在其上使用" getTotallength()"方法。但是相反,我在路径元素的控制台中获得以下输出:
Element: <path d="M11.859375,0.88671875 C9.10229798,32.1448978 3.72401281,62.1847019 0.921875,92.3632812" id="Path"></path>
和" element.getTotallength()"此:
Uncaught TypeError: element.getTotalLength is not a function
我不知道为什么会这样。我希望获得DOM元素并使用" getTotallength()"。
有人知道我在做什么吗?
没有SVG的路径确实支持getTotallength()函数。
它有效
<svg>
<path d={ data } id={ id } ref={ this.refCallback } />
</svg>
您缺少svg
标签,您可以首先分配组件的REF,然后使用DOM方法。
您可以尝试这样的东西
class App extends Component {
componentDidMount() {
console.log(this.pathref.getTotalLength());
}
render() {
const { data, id } = this.props
return(
<svg>
<path ref={(ref) => { this.pathref = ref; }} d={ data } id={ id }></path>
</svg>
)
}
}