reactjs - 打字稿:如何修复此错误->“元素不可分配给字符串”/单击“X”时没有任何反应
问题描述
我正在尝试使用以下代码创建一个弹出横幅(对不起,如果格式关闭)
//this is in folder Banner.tsx
import React, {useCallback} from "react";
type Properties = {
close: () => void;
text: string;
const Banner: React.FC<Properties> = ({close, text}) => {
const onClick = useCallback(() => {
close();},
[close, text]);
return (
<div className = "BannerBox">
<div className = "banner">
<span className = "popup"> {onClick}{close}[x]
</span>
{text}
</div>
</div>
);
};
export default Banner;
//this is in App.tsx
import Banner from "./Components/Banner";
function App(): JSX.Element {
const [isOpen, setIsOpen]=useState(false);
const toggleBanner = () => {
SetIsOpen(!isOpen);
};
return (
<div>
<input type = "button"
value = "popup"
onClick={toggleBanner}/>
<p>hi</p>
{isOpen && <Banner text = {<><b>testing</b><p>testing popup</p><button>testing button</button></>} handleClose={toggleBanner}/>}
</div>
export default App;
但我不断收到此错误,我不确定如何修复它-> type 元素不可分配给键入“string”。错误在这一行: {isOpen && <Banner text = {<> testing
测试弹窗
测试按钮</>} handleClose={toggleBanner}/>}我想我解决了原来的问题,所以现在这就是我的 App.tsx 的样子
import Banner from "./Components/Banner";
function App(): JSX.Element {
const [isOpen, setIsOpen]=useState(false);
const toggleBanner = () => {
SetIsOpen(!isOpen);
};
return (
<div>
<input type = "button"
value = "popup"
onClick={toggleBanner}/>
<p>hi</p>
{isOpen && <Banner text = {"hello"} close={function (): void { throw new Error("Function not implemented.");
} }/>}
</div>
export default App;
但是当我添加css并设置弹出框样式时,按x时它不会关闭。我必须刷新网站才能关闭它,但我不知道如何解决这个问题。没有更多的编译错误。
//this is my Banner.css file (let me know if you need the full code but this is some of it)
.BannerBox{
position: fixed;
background: blue;
width:50%;
}
.banner{
position: relative;
width: 100%;
}
.popup{
content: 'x';
position: fixed;
background: green;
}
解决方案
那是因为在
<Banner text = {<>testing testing popup testing button</>} handleClose={toggleBanner}/>}
text 属性需要一个字符串而不是一个元素。你在这里自己定义了
type Properties = {
close: () => void;
text: string; //this line
推荐阅读
- c# - EF Core:INSERT 语句与 FOREIGN KEY 约束冲突
- css - 如何启用字体变体,如“斜体显示”
- javascript - Cookie 信息弹出制造商 - 在用户拒绝后如何不发送 cookie?
- angular - Angular - Jasmine 单元测试的模拟 Promise 方法
- ruby-on-rails - 检测并删除上传的 ZIP 文件中的所有可执行文件
- google-app-engine - 为自定义域启用 SSL 时未在 Google App Engine 中列出子域
- android - getAppStandbyBucket 需要未知权限
- php - htaccess 404 重定向适用于除 .php 之外的每个扩展名或路径
- angular - 如何在 ngFor 中使用响应式表单
- c# - Enum.GetValues() 是否使用反射?