reactjs - 在 React + TypeScript 中从类组件传递 props

标签 reactjs typescript

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

我的子类(class)如下所示:

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;

最佳答案

您的子组件很好,但您向它传递了错误的 Prop 。

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;

关于reactjs - 在 React + TypeScript 中从类组件传递 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68034996/

相关文章:

javascript - JSDoc/TSDoc 中有没有一种方法可以链接到代码片段?

javascript - 在 if block 中使用 await 时,'await' 对此表达式的类型没有影响

javascript - 从 chrome 开发工具获取 CSS 作为 JavaScript 对象值

javascript - 在 React js 中更改幻灯片时暂停视频?

reactjs - 接下来js导入scss报错(ModuleParseError : Module parse failed: Unexpected character '�' (1:0))

reactjs - 是否可以更改 moment 对象的时区?

reactjs - RTK 查询使用 getState() 从另一个切片获取状态

javascript - 按一定顺序加载多个脚本

typescript - 在 type-graphql 中传递 typescript 类型问题

node.js - WebStorm 与本地的 TypeScript 版本不同