2017-05-02 4 views
2

나는 Full Stack React The Complete Guide를 읽고 그리고이 코드를 통해 온거야 (반작용) 스톱워치 시작 버튼. 이 예제는 공간을 적게 사용하는 방법이 있는지 궁금해했습니다. div를 만든 다음 this.props.timerIsRunning의 값에 따라 해당 div에 특정 속성 및 클래스를 추가하는 방법이 있습니까? 이 예는 JSX 이해의 나의 부족에게 말을하자 ... 그래서가상 DOM 조작은

<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> 

,하지만 난 단지 (1 각도에서 오는 경우 궁금 추측 :이 JSX 아니었다면 나는 이런 식으로 뭔가를 제안 할 것 .X background)에는 ng-show 또는 ng-class에 해당하는 React/JSX가 있습니다. 더 광범위하게는 표준 DOM 조작에 관한 한 가상 DOM과 실제 DOM 사이의 위치가 궁금합니다. React가 JSX를 어떻게 바꾸는 지에 대한 모든 자료는 확실히 도움이 될 것입니다.

답변

3

JSX에서는 특정 장소에서 {} 블록을 사용하여 임의의 JS를 사용할 수 있습니다. 당신은이 장소

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> 
); 

의 각 timerIsRunning를 확인하거나 ng-show의 상응 React conditional rendering 될 것

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> 
); 
+0

:

등가는 (좀) ng-class의이 같은 className 소품을 쓸 수있는 classnames 패키지 (하지 반작용의 일부)입니다! 감사! JSX의 {} 부분 앞에 '$'이 있습니까? 무슨 뜻이에요? 나는 정말로 삼항 논리의 사용을 좋아한다. 슈퍼 깨끗하고 깔끔합니다. –

+0

'className = {}'부분은 JSX이고, 그 curlies 안의 모든 것이 JS이므로,이 경우'$ {running? "red": "green"}'는 표준 ES6 템플릿 리터럴의 표현식입니다 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals – loganfsmyth

+0

나는 그것이 이 기사를 참조하여 템플릿 리터럴 구문 : http://stackoverflow.com/questions/27678052/what-is-the-usage-of-the-backtick-symbol-in-javascript 다시 한 번 감사드립니다. –

0

함께 그룹 일에 destructuring을 사용할 수 있습니다. 이 멋진 대답

return (
    <div 
     className={classnames('ui bottom attached basic button', { 
      red: this.props.timerIsRunning, 
      green: !this.props.timerIsRunning, 
     }) 
     onClick={running ? this.props.onStopClick : this.props.onStartClick} 
    > 
    {running ? "Stop" : "Start"} 
    </div> 
);