我在组件上有几个按钮,这些按钮在通过数组映射时正在呈现。数组中的每个项目都有一个按钮。当我单击特定按钮时,我只希望更改特定索引处该按钮的文本。当前,所有按钮的文本都在更改。我不太确定如何解决该问题。这是我到目前为止的内容:
export default class Profile extends React.Component{
state = {
profile: [],
events: [],
disabledButton: -1,
eventifySent: false
}
static contextType = UserContext
componentDidMount() {
ProfileService.getProfileById(this.props.match.params.id)
.then(profile => {
this.setState({ profile: profile})
const profileId = this.state.profile.user_id
EventService.getAllEvents()
.then( event => {
const profileEvents = event.filter(e => e.event_owner_id === profileId)
this.setState({ events: profileEvents})
})
})
}
handleIntriguedButton = (id, index) => {
EventifyService.postEventify({
recipient_id: this.props.match.params.id,
event: id,
})
.then( response => {
console.log(response)
this.setState({
disabledButton: index,
eventifySent: true
}) }
)
}
render() {
const user = this.state.profile
const events = this.state.events
console.log(this.state.disabledButton)
const userEvents = (events.length === 0 ) ? 'I have no events yet'
: events.map((event, i) =>
<div key={event.id} className="event">
<p>{event.event_name}</p>
<button type="submit" disabled={this.state.disabledButton === i} onClick={() => this.handleIntriguedButton(event.id, i)}>{!this.state.eventifySent && this.state.disabledButton !== i ? ('Intrigued') : ('Eventify sent!')}</button>
</div>
)
return (
<div className="profile">
<img src={user.profile_picture} alt=''/>
<p>Bio: {user.me_intro}</p>
<ul>
<li>Music: {user.music_like}</li>
<li>Favorite movie: {user.movie_like}</li>
</ul>
<p>Events:</p>
<div className="profile-events">
{userEvents}
</div>
</div>
)
}
}
我以为我正在选择该按钮的特定索引,但是我想没有。谢谢。
答案 0 :(得分:0)
将eventifySent设置为true时,此表达式的计算结果始终为false:
!this.state.eventifySent && this.state.disabledButton !== i
因此,您总是会被“吸引”。
如果稍微转一下,它应该可以工作:
this.state.eventifySent && this.state.disabledButton === i ? 'Eventify Sent' : 'Intrigued'