css - نوع 'string' قابل اختصاص به نوع 'Position' نیست
من در حال حاضر React js را به ts تغییر میدهم. این یک کامپوننت کلاسی است.
میخواهم تنظیمات CSS را از props دریافت کنم و آن را به عنصر اعمال کنم.
چطور باید این را تعمیر کنم؟
render(){return(
<span style={{
position: this.props.position ,
left: this.props.left,
top: this.props.top,
height: this.props.height,
width: this.props.width
}} /> </span>)}
پاسخ شماره ۱
تایپاسکریپت انتظار دارد رشته بهطور دقیق یکی از گزینههای خاص ویژگی position باشد - absolute، relative و غیره. یکی از راههای حل این مشکل این است که به آن بگویید میدانید نوع داده درست خواهد بود، مانند این:
<span style={{
position: this.props.position,
left: this.props.left,
top: this.props.top,
height: this.props.height,
width: this.props.width
}: as React.CSSProperties} /> </span>)}
گزینهی دیگر این است که به جایی بروید که ویژگی position در ابتدا تعریف شده است (عنصر والد) و بگذارید تایپاسکریپت نوع را اعمال کند، برای مثال:
const styles: ('absolute' | 'relative' | 'fixed') = 'absolute';
پاسخ شماره ۲
نیازی به تبدیل شیء نیست، بلکه هنگام مقداردهی اولیه نوع React.CSSProperties را اعلام کنید.
function MyComponent(props) {
const styles: React.CSSProperties = {
position: this.props.position,
left: this.props.left,
top: this.props.top,
height: this.props.height,
width: this.props.width
};
return (
<span style={styles}></span>
);
}
