[英]How to rewrite JS Progressbar.js object to React component
我在React玩了幾天,一切似乎都相當輕松,直到我陷入將這個JS對象重寫為React組件的困境。
這是帶有JS對象示例的JsFiddle示例。 如何將其重寫為React組件?
這是我正在嘗試的:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import ProgressBar from 'progressbar.js';
class Circle extends Component{
componentDidMount() {
this._create(this.props);
}
_create(props) {
var container = ReactDOM.findDOMNode(this.refs.progressBar);
container.animate(props.progress);
}
render() {
return <div ref="progressBar"></div>;
}
}
Circle.defaultProps = {
options: {},
progress: 1.0,
}
export default Circle;
這是一個加載圓的例子,
但不會從上面的代碼中進行修改。
相反,我使用SVG , strokeDashArray和strokeDashOffset
碼
import React from 'react';
const styles = {
svg :{
position:'fixed',
width:'100%',
height:'100%',
position:'fixed',
top:'0', left:'0',
background:'rgba(240,240,240,1)',
},
circle : {
strokeDasharray : '300',
transition : 'all .4s ease-in',
},
}
export default class Loading extends React.Component {
constructor(props){
super(props);
let screenSize = this._calculateDevice();
this.state = { offset:600,
cx:screenSize.width/2,
cy:screenSize.height/2,
r:50,
}
this._unmount = this._unmount.bind(this);
}
_calculateDevice() {
let width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
let height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
return {width, height}
}
componentDidMount (){
this.interval = setInterval(() => {
const offset = this.state.offset - 50;
this.setState({offset: offset });
},200);
}
componentWillUnmount() {
clearInterval(this.interval);
}
_unmount () {
this.setState({loaded:true});
}
_circlePath (){
let d = `M${this.state.cx},${this.state.cy}a${this.state.r},${this.state.r} 0 1,0 100,0a${this.state.r},${this.state.r} 0 1,0 -100,0`;
return d
}
render (){
let d = this._circlePath();
let style = Object.assign({}, styles.circle, {'strokeDashoffset':this.state.offset});
let svgStyle = styles.svg;
return(
<svg style={svgStyle}>
<path
stroke = "#AAA"
strokeWidth = "5px"
fill = "none"
d = {d}
/>
<path
style = {style}
stroke = "#D22"
strokeWidth = "5px"
fill = "none"
d = {d}
/>
</svg>
)
}
}
簡要說明
componentDidMount (){
this.interval = setInterval(() => {
const offset = this.state.offset - 50;
this.setState({offset: offset });
},200);
}
setInterval中的函數將更新偏移量,還將創建新路徑。
_circlePath (){
let d = `M${this.state.cx},${this.state.cy}a${this.state.r},${this.state.r} 0 1,0 100,0a${this.state.r},${this.state.r} 0 1,0 -100,0`;
return d
}
並且此函數將創建路徑,該路徑決定svg中圓的外觀。
這樣我們就可以通過改變路徑來實現旋轉圈的效果
注意
由於setInterval函數
我們需要記住清除組件卸下之前的間隔
以避免setInterval在不存在的組件上崩潰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.