简体   繁体   English

反应:帮助有条件地渲染btn

[英]REACT:Help conditionally rendering btn

I cant get a button to show "shortlist" then change to "remove" when conditionally rendered. 我无法显示有条件的按钮来显示“候选列表”,然后更改为“删除”。 It is changing in state from true to false and back to true but the button wont change in the Btn component! 它的状态从true变为false,然后又返回true,但是按钮在Btn组件中不会改变!

Here is where it is rendered in app: 这是在应用程序中呈现的位置:

{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>
    )
  })}

Here is state and the function in app: 这是状态和应用程序中的功能:

         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]})
}

Here is the btn component: 这是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;

You need a correction on your render method, it should be like: 您需要对render方法进行更正,它应该像这样:

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

Also, your onFavorite method should be like: 另外,您的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});
  }
}

And each button on your map should be passing different props: 并且地图上的每个按钮都应传递不同的道具:

{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} ?

doesn't mean anything. 没什么意思 You're passing this.props.shortlist as a boolean. 您将this.props.shortlist作为布尔值传递。 true:true is not valid anything true:true无效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM