簡體   English   中英

反應:幫助有條件地渲染btn

[英]REACT:Help conditionally rendering btn

我無法顯示有條件的按鈕來顯示“候選列表”,然后更改為“刪除”。 它的狀態從true變為false,然后又返回true,但是按鈕在Btn組件中不會改變!

這是在應用程序中呈現的位置:

{filteredApplicants.map((applicant) => {
    return(<div className='applications'> <ul >
      <li  className='applicant-li' key={applicant.id}> <h5>{applicant.name} - {applicant.position}</h5>
        <p></p>
        <Btn onFavorite={() => this.onFavorite(applicant)} shortlist={this.state.showShortlist} />
      </li></ul> </div>
    )
  })}

這是狀態和應用程序中的功能:

         searchField:'',
          saved:[],
          positions:[],
          showShortlist: true
      }
    }
onFavorite = applicant => {
  const { saved, showShortlist } = this.state; 
  console.log(showShortlist)
  if(this.state.saved.includes(applicant)){
    this.setState({showShortlist:!showShortlist})
  } else
   this.setState({
    saved:[...saved, applicant]})
}

這是btn組件:

import React,{Component} from 'react';

class Btn extends Component{
    constructor({shortlist}){
        super({shortlist})
    }
    render(){

        const remove = <button>Remove</button> 
        const add = <button>Shortlist</button>  
        console.log(this.props.shortlist)
        return(

            {shortlist:true} ? <button onClick={this.props.onFavorite}>Remove</button>:<button>Shortlist</button>  
        )
    }
}

export default Btn;

您需要對render方法進行更正,它應該像這樣:

    render() {
      const {shortlist, onFavorite} = this.props;
      return (<button onClick={onFavorite}>{shortlist ? 'Remove' : 'Add Favorite'}</button>);
    }

另外,您的onFavorite方法應類似於:

onFavorite = applicant => {
  const { saved } = this.state; 
  const index = saved.indexOf(applicant);

  if(index === -1) {
   this.setState({
    saved: [...saved, applicant],
   });
  } else {
    saved.splice(index, 1);
    this.setState({saved});
  }
}

並且地圖上的每個按鈕都應傳遞不同的道具:

{filteredApplicants.map((applicant) => {
return (<div className='applications'> <ul>
  <li className='applicant-li' key={applicant.id}> <h5>{applicant.name} - {applicant.position}</h5>
    <p></p>
    <Btn onFavorite={() => this.onFavorite(applicant)} shortlist={this.state.saved.includes(applicant)} />
  </li></ul> </div>
)
})}
{shortlist:true} ?

沒什么意思 您將this.props.shortlist作為布爾值傳遞。 true:true無效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM