2 回答
TA贡献1866条经验 获得超5个赞
您的解决方案可以通过仅在状态为 false 时隐藏段落而不更改整个返回值来简化一点。
class Message extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: 0
};
}
clickHandler = e => {
e.preventDefault();
this.setState({
visible: !this.state.visible
});
};
render() {
return (
<React.Fragment>
<a href="#" onClick={this.clickHandler}>
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);
TA贡献1827条经验 获得超8个赞
我用来通过测试用例的解决方案
class Message extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: 1
};
}
clickHandler = e => {
e.preventDefault();
this.setState({
visible: !this.state.visible
});
};
render() {
return this.state.visible ? (
<React.Fragment>
<a href="#" onClick={this.clickHandler}>
Want to buy a new car?
</a>
</React.Fragment>
) : (
<React.Fragment>
<a href="#" onClick={this.clickHandler}>
Want to buy a new car?
</a>
<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);
添加回答
举报