我收到包含“this.props.isCompleted?”的行的错误消息说“this”是一个意外的关键字,我不明白为什么,因为我使用的是类组件。这实际上是我去年参与的一个旧项目,它运行良好,但今天是我再次查看它的第一天,我不知道为什么我现在会收到该错误。
import React from "react";
class Todo extends React.Component {
state = {
checked: false
};
handleCheck = () => {
//allows you to check and uncheck
this.setState({
checked: !this.state.checked
});
};
handleClick = () => {
this.props.handlecompletedList({
title: this.props.title
});
};
handleDeleteTask = () => {
this.props.deleteTask(this.props);
};
render() {
const { title } = this.props;
let current_date = new Date();
let formatted_date =
current_date.getMonth() +
1 +
"/" +
current_date.getDate() +
"/" +
current_date.getFullYear();
return (
{
this.props.isCompleted?
<div>
{title}
</div>
:
<div className="ui checked checkbox">
<input
type="checkbox"
checked={this.state.checked}
onChange={this.handleCheck}
onClick={this.handleClick}
/>
<label
style={{
textDecorationLine: this.state.checked ? "line-through" : "none",
textDecorationStyle: "solid",
textDecorationColor: "red"
}}
>
{title}
</label>
<button
onClick={this.handleDeleteTask}
style={{
backgroundColor: "indigo",
color: "white",
position: "absolute",
right: "-50px",
top: "-5px"
}}
className="mini ui button"
>
{" "}
X{" "}
</button>
<p
style={{
fontFamily: "cursive",
color: "purple",
position: "absolute",
right: "-115px",
top: "0px"
}}
>
{formatted_date}
</p>
</div>
}
);
}
}
export default Todo;
答案 0 :(得分:1)
您的 JSX 语法无效。
它至少需要被一个 <></>
标签包围,让 react 识别你在大括号中的 JS 表达式。
查看 docs 以了解 JSX 的实际工作原理。
return (
<>
{this.props.isCompleted ?
<div> {title} </div>
:
<div>something else</div>
}
</>
);
请注意,<></>
是 React.Fragment
的简写。
或者,您也可以通过跳过 JSX 特殊的嵌入式 JS 来使用 vanilla JS 进行分支。
return (
this.props.isCompleted ?
<div> {title} </div>
:
<div>something else</div>
);
答案 1 :(得分:0)
HTML 中不需要 this
。你只在方法中使用它
return ( { props.isCompleted ?
<div>
{title}
</div>
:
<div className="ui checked checkbox"></div>
});