我试图解决testdome上的一个React问题.
这就是任务:
消息组件包含一个锚元素和锚下的一段.应通过使用以下逻辑单击锚点元素来切换段落的呈现:
At the start, the paragraph should not be rendered.
After a click, the paragraph should be rendered.
After another click, the paragraph should not be rendered.
Finish the Message component by implementing this logic.
这就是解决方案:
// React is loaded and is available as React and ReactDOM
// imports should NOT be used
class Message extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: false
};
}
clickHandler = (event) => {
event.preventDefault();
this.setState({
visible: !this.state.visible
});
}
render() {
return (<React.Fragment>
<a onClick={this.clickHandler} href="#">Want to buy a new car?</a>
{ this.state.visible && <p>Call +11 22 33 44 now!</p>}
</React.Fragment>);
}
}
document.body.innerHTML = "<div id='root'> </div>";
const rootElement = document.getElementById("root");
ReactDOM.render(<Message />, rootElement);
console.log("Before click: " + rootElement.innerHTML);
document.querySelector("a").click();
console.log("After click: " + rootElement.innerHTML);
我想用useState钩子做同样的事情.这是我的代码:
// React is loaded and is available as React and ReactDOM
// imports should NOT be used
class Message extends React.Component {
const [show, setShow] = useState(false);
const toggleVisibility = () => {
setShow(!show);
}
render() {
if(show) {
return (<React.Fragment>
<a onClick={toggleVisibility} href="#">Want to buy a new car?</a>
<p>Call +11 22 33 44 now!</p>
</React.Fragment>);
} else {
return (<React.Fragment>
<a onClick={toggleVisibility} href="#">Want to buy a new car?</a>
</React.Fragment>);
}
}
}
document.body.innerHTML = "<div id='root'> </div>";
const rootElement = document.getElementById("root");
ReactDOM.render(<Message />, rootElement);
console.log("Before click: " + rootElement.innerHTML);
document.querySelector("a").click();
console.log("After click: " + rootElement.innerHTML);
这是输出:
Run OK, but 3 out of 3 test cases failed.
Line 5: SyntaxError: unknown: Unexpected token (5:8)
3 | class Message extends React.Component {
4 |
> 5 | const [show, setShow] = useState(false);
| ^
6 |
7 | const toggleVisibility = () => {
8 | setShow(!show);
Your score is 0% :(
为什么它不起作用?不允许在类组件中使用挂钩吗?