문제

ON 및 OFF 상태에 대해 2개의 서로 다른 이미지 사이를 전환하는 사용자 정의 이미지 버튼을 표시하는 이 ReactJS 코드가 있습니다.이를 수행하는 더 간단한 방법이 있습니까?CSS가 코드 줄이 줄어들기를 바랐지만 간단한 예를 찾을 수 없었습니다.

아래 코드는 상태를 위로 전달합니다. <MyIconButton> 에게 <MyPartyCatButton> 그럼 <MyHomeView>.내 앱의 홈 화면에는 이러한 맞춤 버튼이 4개 있으므로 제외했습니다. <MyIconButton>.

그런데 - 이것은 모바일 앱을 위한 것이며 제가 읽었으며 (그리고 이것을 직접 알아차렸습니다) 모바일 브라우저에서 체크박스를 사용하면 정말 느립니다.그래서 나는 체크박스를 사용하지 않고 이것을 시도하기로 결정했습니다.

ReactJS 코드

var MyIconButton = React.createClass({

  handleSubmit: function(e) {
    e.preventDefault();
    console.log("INSIDE: MyIconButton handleSubmit");

    // Change button's state ON/OFF, 
    // then sends state up the food chain via            
    //  this.props.updateFilter( b_buttonOn ).
    var b_buttonOn = false;
    if (this.props.pressed === true) {
      b_buttonOn = false;
    }
    else {
      b_buttonOn = true;
    }
    // updateFilter is a 'pointer' to a method in the calling React component.
    this.props.updateFilter( b_buttonOn ); 
  },

  render: function() {

    // Show On or Off image.
    // ** I could use ? : inside the JSX/HTML but prefer long form to make it explicitly obvious. 
    var buttonImg = "";
    if (this.props.pressed === true) {
      buttonImg = this.props.onpic;
    }
    else {
      buttonImg = this.props.offpic;
    }

    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input type="image" src={buttonImg}></input>
        </form>
      </div>
    );
  }
});


// <MyPartyCatButton> Doesn't have it's own state, 
// passes state of <MyIconButton> 
// straight through to <MyHomeView>.
var MyPartyCatButton = React.createClass({

  render: function() {
    return (
      <MyIconButton pressed={this.props.pressed} updateFilter={this.props.updateFilter} onpic="static/images/icon1.jpeg" offpic="static/images/off-icon.jpg"/>
    );
  }
});

//
// Main App view
var MyHomeView = React.createClass({
  getInitialState: function() {
    // This is where I'll eventually get data from the server.
    return {
      b_MyPartyCat: true
    };
  },

  updatePartyCategory: function(value) {
    // Eventually will write value to the server.
    this.setState( {b_MyPartyCat: value} );
    console.log("INSIDE: MyHomeView() updatePartyCategory() " + this.state.b_MyPartyCat );
  },

  render: function() {
    return (
        <div>
         <MyPartyCatButton pressed={this.state.b_MyPartyCat} updateFilter={this.updatePartyCategory}/>
        </div>

        // Eventually will have 3 other categories i.e. Books, Skateboards, Trees !
    );
  }
});
도움이 되었습니까?

해결책

당신이 했던 것처럼 '눌려진' 구성요소 소품을 동적으로 업데이트한다면, 간단하게

var MyIconButton= React.createClass({
    render: function(){
        var pic= this.props.pressed? this.props.onpic : this.props.offpic
        return <img 
            src={pic} 
            onClick={this.props.tuggleSelection}  //updateFilter is wierd name
        />
    }
})

(편집하다:이렇게 하면 MyPartyCatButton 구성 요소에서 'tuggleSelection' 이벤트를 처리하는 함수를 전달할 수 있습니다.이벤트 함수 인수는 이벤트 객체, 그러나 래퍼 상태에 이미 버튼 상태가 있습니다(이전 상태이므로 반전해야 함).귀하의 코드는 다음과 같습니다.

render: function(){
    return <MyIconButton pressed={this.state.PartyCatPressed} tuggleSelection={this.updatePartyCategory} />
}
updatePartyCategory: function(e){
    this.setState( 
        {PartyCatPressed: !this.state.PartyCatPressed} //this invert PartyCatPressed value
    );
    console.log("INSIDE: MyHomeView() updatePartyCategory() " + this.state.b_MyPartyCat )
}

)

하지만 그렇지 않은 경우 기본값으로 prop을 사용하세요.

var MyIconButton= React.createClass({
    getInitialState: function(){
        return {pressed: this.props.defultPressed}
    },
    handleClick: function(){
        this.setState({pressed: !this.state.pressed})
    },

    render: function(){
        var pic= this.state.pressed? this.props.onpic : this.props.offpic
        return <img 
            src={pic} 
            onClick={this.handleClick}
        />
    }
})
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top