传递给函数的样式属性的类型

IT技术 reactjs typescript
2021-05-08 20:04:44

请考虑这个typescript功能

 function button(style: any, func: ()=>void, img: string) {
    return (
      <button
        className="Reader_Button"
        style={style}
        onClick={func}
      >
        <img src={img} alt="" />
        Back
      </button>
    );
  }

第一个参数的正确类型是什么style我觉得它应该是 HTMLElementStyle 之类的东西,但我找不到正确的咒语。

抱歉,我说的不够清楚。我想知道用什么类型来替换style: any. typescript定义处理检查提供的对象成员的类型。

我在谈论功能的定义,而不是应用程序。

3个回答

类型是React.CSSProperties你可以在 VSCode 中找到它,方法是在你的光标在属性中写下<div style={{}}>并按下F12style

常规 DOM 元素上的 style 属性应该是一个对象的形式,其中键是 css 属性。

例子: <div style={{ width: "100%", backgroundColor: "black" }} />

请注意,在包含破折号的属性的情况下,它们会变成驼峰式。例如background-color变成backgroundColor.

React 风格文档

对我来说,“从 csstype 导入 CSS” && 换行到引号 'maxHeight': '120px'

import React from 'react';
import CSS from 'csstype';
    
const shortList = () => {
    const listStylus: CSS.Properties = {
        'maxHeight': '120px',
        'overflow': 'hidden',
      }
    
      return (
        <div>
          <ul style={listStylus} >
            <li>Item element 1</li>
            <li>Item element 2</li>
          </ul>
        </div>
      )
}

export default shortList