如何将值从组件传递到变量

时间:2019-02-18 07:48:47

标签: reactjs react-native

我有一个使用动画部件的组件。我希望将组件的返回值传递给变量。

我试图喜欢这个

const temp = <Counter end={500}/>

但是我得到的响应是[object,object]

const temp = <Counter end={needleAngle}/>;

计数器组件:

export default class Counter extends Component {
  static propTypes = {
    start: PropTypes.number,
    end: PropTypes.number.isRequired,
    digits: PropTypes.number,
    time: PropTypes.number,
    easing: PropTypes.string,
    onComplete: PropTypes.func,
    style: PropTypes.any,
  };

  static defaultProps = {
    start: 0,
    digits: 0,
    time: 1000,
    easing: 'linear',
  };

  state = { value: this.props.start };

  componentDidMount() {
    this.startTime = Date.now();
    requestAnimationFrame(this.animate.bind(this));
  }

  animate() {
    const { onComplete } = this.props;

    if (this.stop) {
      if (onComplete) onComplete();
      return;
    }

    requestAnimationFrame(this.animate.bind(this));
    this.draw();
  }

  draw() {
    const { time, start, end, easing } = this.props;

    const now = Date.now();
    if (now - this.startTime >= time) this.stop = true;
    const percentage = Math.min((now - this.startTime) / time, 1);
    const easeVal = eases[easing](percentage);
    const value = start + (end - start) * easeVal;

    this.setState({ value });
  }

  render() {
    const { digits } = this.props;
    const { value } = this.state;

    return (
      // <Text style={style}>{value.toFixed(digits)}</Text>
      value.toFixed(digits)
    );
  }
}

如上所述,我要强调这一部分。

1 个答案:

答案 0 :(得分:-1)

如果您尝试从案例Counter组件中的自定义动画组件中获取动画值或任何值,则可以传递箭头函数作为回调并接收如下所述的值:

const temp = <Counter end={500} callBack={(value) => console.log(value)}/>

Counter组件中,您可以从组件中的任何位置调用回调,如下所示:

this.props.callBack(value);