反应使用打字稿发送道具

时间:2019-10-08 09:34:09

标签: reactjs typescript

接收颜色的颜色组件会抛出道具并产生颜色效果。

clean()

将道具发送到颜色组件的ParentComponent

export enum Colors {
  Blue = "333CFF",
  Yellow = "FCFF33",
  Green = "33FF36",
}

interface IColorProps {
  myColors: Colors ;
}

export const ColorComponent: FunctionComponent<IColorProps > = ( {props: IColorProps } => {
    return (
    <div className={`colorCalss ${props.bgColor}`} />
 )});

以下是我放入IParentComponentProps中的内容

import { ColorComponent, Colors } from "ColorComponent.component";

export const ParentComponent: FunctionComponent<IParentComponentProps> =
(props: IParentComponentProps) => {

        <ColorComponent myColors={Colors.Blue}/>
}

我刚开始使用打字稿。

上面的Parent组件将myColors道具发送给ColorComponent,它的工作原理我可以看到蓝色应用于测试。

如何将道具动态发送到ColorComponent,例如,让parent.component props.color获得可以应用的不同颜色。

当我执行以下操作:“ <” ColorComponent myColors = {props.colors} /“>”时,我会收到错误消息。

如何使用枚举使道具动态传递?

2 个答案:

答案 0 :(得分:1)

您的父界面应该具有相同的颜色类型:

export interface IParentComponentProps {
  colors: Colors; 
}

这样,您就不会出现类型错误,并且可以传递颜色道具。

或向下传递props.colors.myColors变量。但是请注意,它可能不存在,因为它具有可选功能。

答案 1 :(得分:0)

您无需执行任何特殊操作即可将颜色动态发送给孩子。专门针对打字稿,只需确保所有类型都是一致的即可。

您的示例中有一些语法错误,因此也许它不是为您编译的吗?

这是一个工作示例,其中父组件动态更改颜色并将其每秒发送给孩子。

export enum Colors {
  Blue = "333CFF",
  Yellow = "FCFF33",
  Green = "33FF36",
}

interface IColorProps {
  color: Colors;
}

export const ColorComponent: React.FunctionComponent<IColorProps> = (props: IColorProps) => {
  return <div style={{ backgroundColor: `#${props.color}`, height: '100px', width: '100px' }} />
};

const ParentComponent: React.FC = () => {

  const colors = [Colors.Blue, Colors.Green, Colors.Yellow];
  const [color, setColor] = React.useState(0);
  const { current } = React.useRef({ next: function() { } });

  current.next = () => {
    const nextColor = (color === 2) ? 0 : (color + 1);
    setColor(nextColor);
  };

  useEffect(
    () => {
      const interval = setInterval(() => current.next(), 1000);
      return () => clearInterval(interval);
    },
    []
  );

  return (
    <>
      <h1>Current color is #{colors[color]}</h1>
      <ColorComponent color={colors[color]}/>
    </>
  );

}