我正在阅读Full Stack React The Complete Guide并发现了这个代码片段:
render() {
if(this.props.timerIsRunning){
return(
<div
className='ui bottom attached red basic button'
onClick={this.props.onStopClick}
>
Stop
</div>
)
} else {
return(
<div
className='ui bottom attached green basic button'
onClick={this.props.onStartClick}
>
Start
</div>
)
}
}
它使用 if 语句来确定组件将呈现的内容,秒表的停止或开始按钮。这个例子让我想知道是否有一种方法可以使用更少的空间来做到这一点。有没有办法创建 div,然后根据 this.props.timerIsRunning 的值向该 div 添加某些属性和类?如果这不是 JSX,我会提出这样的建议:
<div id=timerbutton></div>
<script>
let timerButtonDiv = document.getElementById(timerbutton)
if(this.props.timerIsRunning) {
timerbuttonDiv.className = 'ui bottom attached red basic
button'
timerbuttonDiv.innerHTML = Stop
} else {
timerbuttonDiv.className = 'ui bottom attached green basic
button'
timerbuttonDiv.innerHTML = Start
}
</script>
所以...让这个例子说明我对 JSX 理解的缺乏,但我想,我只是想知道(来自 Angular 1.X 背景)是否有一个与 ng-show 或 ng 等效的 React/JSX -类(class)。更广泛地说,我想知道就标准 DOM 操作而言,虚拟 DOM 和实际 DOM 之间的界线在哪里。任何关于 React 如何转置 JSX 的资源肯定会有帮助。
最佳答案
JSX 允许您在某些地方使用 {}
block 来使用任意 JS。您可以在每个位置检查 timerIsRunning
const running = this.props.timerIsRunning;
return (
<div
className={
`ui bottom attached ${running ? "red" : "green"} basic button`
}
onClick={running ? this.props.onStopClick : this.props.onStartClick}
>
{running ? "Stop" : "Start"}
</div>
);
或者使用解构将事物组合在一起
const {color, handler, text} = this.props.timerIsRunning ? {
color: "red",
handler: this.props.onStopClick,
text: "Stop",
} : {
color: "greed",
handler: this.props.onStartClick,
text: "Start",
};
return (
<div
className={`ui bottom attached ${color} basic button`}
onClick={handler}
>
{text}
</div>
);
关于ecmascript-6 - JSX 中的虚拟 DOM 操作 (React),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43728464/