在反应 + 打字稿中从类组件传递道具

时间:2021-06-18 12:14:19

标签: reactjs typescript

我是 typescript 的新手,想知道如何将 prop 从我的类组件传递给父类。

我的子类看起来像这样:

import React from "react";

type Props = {
startTimeInSeconds: number;
}

type State = {
timeRemainingInSeconds: number;
}


export default class Child extends React.Component<Props, State>{
    private timer: any;

constructor(props: Props) {
  super(props);
  this.state = {
    timeRemainingInSeconds: props.startTimeInSeconds
  };
}

decrementTimeRemaining = () => {
  if (this.state.timeRemainingInSeconds > 0) {
    this.setState({
      timeRemainingInSeconds: this.state.timeRemainingInSeconds - 1
    });
  } else {
    clearInterval(this.timer!);
  }
};

componentDidMount() {
  this.timer = setInterval(() => {
    this.decrementTimeRemaining();
  }, 1000);
}

render() {
  return (
    <div className="countdown-timer">
      <div className="countdown-timer__circle">
        <svg>
          <circle
            r="24"
            cx="26"
            cy="26"
            style={{
              animation: `countdown-animation ${this.props
                .startTimeInSeconds}s linear`
            }}
          />
        </svg>
      </div>
      <div className="countdown-timer__text">
        {this.state.timeRemainingInSeconds}s
      </div>
    </div>
  );
}
}

我想在我的父组件中调用这个子组件,但我不明白它是如何工作的。 我试图用

调用父级中的孩子

<Child startTimeInSeconds = { this.startTimeInSeconds } />

但它会抛出一个错误。

(简化的)父组件如下所示:

import '../css/App.css';
import * as React from "react";
import Child from "./ChildComponent"

function App(props) {
  return (
    <>
    <div>
        <Child startTimeInSeconds = { this.startTimeInSeconds } />
    </div>
    </>
  );
}

export default App;

1 个答案:

答案 0 :(得分:1)

您的 Child 组件很好,但是您传递给它的道具不正确。

App 组件中,您需要定义 startTimeInSeconds 变量>

你的父组件应该是这样的 -

import '../css/App.css';
import * as React from "react";
import Child from "./ChildComponent"

function App(props) {
  const startTimeInSeconds = 0; //or any number
  return (
    <>
    <div>
        <Child startTimeInSeconds = { startTimeInSeconds } />
    </div>
    </>
  );
}

export default App;