React Typescript 语法

Children

interface Props {
  children?: React.ReactNode
}

 

Events

interface Props {
  // 事件对象
  onClick?: (event: MouseEvent<HTMLButtonElement>) => void
}

 

props对象中用buttonProps对象作为button的属性

interface Props {
  buttonProps?: JSX.IntrinsicElements['button']
}
const Container = ({ buttonProps }: Props) => (
  <div>
    <button {...buttonProps}></button>
  </div>
)

 

整个props对象都作为button的属性

interface Props extends JSX.IntrinsicElements['button'] {}
const ExtendedButton = (props: Props) => (
  <button {...props} />
)

 

Styles

// utils.d.ts
declare interface StyleProps {
  style?: React.CSSProperties
  className?: string
}
// Button.tsx
interface ButtonProps extends StyleProps {
  label: string
}
const Button = ({ label, ...styleProps }: ButtonProps) => (
  <button {...styleProps}>{label}</button>
)

 

Refs

const liRef = useRef<HTMLLIElement>(null)
Other refs are possible too:
const valueRef = useRef<number>(0)

 

在Typescript使用函数组件

export interface Props {
  defaultCount: number
}
export default function MyCounter({ defaultCount = 0 }: Props): React.ReactElement {
  const [count, setCount] = React.useState<number>(defaultCount);
  const incrementCount = () => {
    setCount(count + 1);
  }
  return <button onClick={incrementCount}>Example - count: {count}</button>
}

 

函数组件是箭头函数

const MyComponent: React.FC<Props> = ({ value }) => <div>Syntax</div>

 

在Typescript使用类组件

interface Props {
  value: number
}
interface State {
  text: string
}
class MyComponent extends React.Component<Props, State> {
  static defaultProps: Props = {
    value: 0
  }
  state: State = { text: 'Example' }
  render() {
    return <div>Syntax {this.props.value} {this.state.text}</div>
  }
}

 

为了描述“children”,我更喜欢使用React.FC泛型类型。

interface AnotherSpecificProps {}
const AnotherComponent: React.FC<AnotherSpecificProps> = ({ children }) => {};
// even with omitted props it's still working
const Component: React.FC = ({ children }) => {};

 

有时我需要向嵌套组件传递额外的props,你也可以用部分<React.ComponentProps<typeof SomeComponent>>来包装它。

ComponentProps {
  prop: boolean;
  propAnother: string;
}
const Component: React.FC<ComponentProps> = ({prop, propAnother}) => {
  return (
    <div>
      {prop && propAnother}
    </div>
  );
};
interface ComplexComponentProps {
  componentProps?: Partial<React.ComponentProps<typeof Component>>
}
const ComplexComponent: React.FC<ComplexComponentProps> = ({componentProps}) => {
  return (
    <div>
      <Component prop={true} propAnother="string" {...componentProps} />
    </div>
  );
};
// somewhere else
<ComplexComponent />
<ComplexComponent componentProps={{prop: false}} />
// without Partial you should pass all required props, so Partial is very useful

 

React.ComponentProps <typeof Component>看起来特别有用,可用于向下传递props而无需导入子组件的Props接口。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.duanlonglong.com/qdjy/651.html