如何使用 React 切换消息(Test-Dome 解决方案1)

Message 组件包含一个锚元素和锚下方的一个段落。段落的渲染应该通过使用以下逻辑单击锚元素来切换:

在开始时,不应呈现该段落。单击后,应呈现该段落。再次单击后,不应呈现该段落。


犯罪嫌疑人X
浏览 122回答 2
2回答

心有法竹

您的解决方案可以通过仅在状态为 false 时隐藏段落而不更改整个返回值来简化一点。class Message extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; visible: 0&nbsp; &nbsp; };&nbsp; }&nbsp; clickHandler = e => {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; visible: !this.state.visible&nbsp; &nbsp; });&nbsp; };&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <React.Fragment>&nbsp; &nbsp; &nbsp; &nbsp; <a href="#" onClick={this.clickHandler}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Want to buy a new car?&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; &nbsp; {this.state.visible && <p>Call +11 22 33 44 now!</p>}&nbsp; &nbsp; &nbsp; </React.Fragment>&nbsp; &nbsp; );&nbsp; }}document.body.innerHTML = "<div id='root'> </div>";const rootElement = document.getElementById("root");ReactDOM.render(<Message />, rootElement);

斯蒂芬大帝

我用来通过测试用例的解决方案class Message extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; visible: 1&nbsp; &nbsp; };&nbsp; }&nbsp; clickHandler = e => {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; visible: !this.state.visible&nbsp; &nbsp; });&nbsp; };&nbsp; render() {&nbsp; &nbsp; return this.state.visible ? (&nbsp; &nbsp; &nbsp; <React.Fragment>&nbsp; &nbsp; &nbsp; &nbsp; <a href="#" onClick={this.clickHandler}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Want to buy a new car?&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; </React.Fragment>&nbsp; &nbsp; ) : (&nbsp; &nbsp; &nbsp; <React.Fragment>&nbsp; &nbsp; &nbsp; &nbsp; <a href="#" onClick={this.clickHandler}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Want to buy a new car?&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; &nbsp; &nbsp; <p>Call +11 22 33 44 now!</p>&nbsp; &nbsp; &nbsp; </React.Fragment>&nbsp; &nbsp; );&nbsp; }}document.body.innerHTML = "<div id='root'> </div>";const rootElement = document.getElementById("root");ReactDOM.render(<Message />, rootElement);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript