我玩了几天 React,一切看起来都相当容易,直到我坚持将这个 JS 对象重写为 React 组件。
这是JsFiddle Example以 JS 对象为例。如何将其重写为 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、中风DashArray 和 中风DashOffset
代码
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 在不存在的组件上崩溃。
关于javascript - 如何将JS Progressbar.js对象重写为React组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37625514/