我无法显示有条件的按钮来显示“候选列表”,然后更改为“删除”。它的状态从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;
答案 0 :(得分:0)
您需要对渲染方法进行更正,就像:
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>
)
})}
答案 1 :(得分:0)
{shortlist:true} ?
没什么意思。您将this.props.shortlist作为布尔值传递。 true:true无效。