在react中,我只想选择一个用户,我的代码正在选择每个用户



当我点击添加朋友按钮时,我面临的问题是每个按钮都更改为请求,我怎么能特别将它设置为一个用户,我点击了一些东西,但它不工作,它选择了其他用户。我使用了handleproductselect函数但它不起作用我给了他们个人id仍然不起作用

class SearchModal extends Component {
constructor(props){
super(props);
this.state = {
Input:"Add Friend",
backgroundColor: 'white',
active_id: null,
}
}
async handleProductSelect(elementid){
const id = elementid;
const { backgroundColor } = this.state;
let newBackgroundColour = backgroundColor === 'white' ? 'yellow' : 'white';
this.setState({ 
Input : "Requested",
backgroundColor: newBackgroundColour,
active_id: id
})
console.log(id)
}
render() {
const {currentUser} = this.props;
return (
<div>
<Modal show={this.state.show} onHide={this.handleClose} 
>
<Modal.Header closeButton>
<Modal.Title>
<input 
type="text" 
placeholder="Search.."
value={search}
onChange={this.onTextboxChangeSearch}
></input>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<h3>Users</h3>
<div>
<ul className="collection">
{userdetails.map((element) => {
if(currentUser.user.username !== element.username){
return(
<div key={element._id}>
<li>{element.username}{' '}<input 
type="button" 
id={element._id} 
onClick={this.handleProductSelect.bind(this,element._id )} 
value={this.state.Input} 
style = {{backgroundColor: ( element._id === this.state.active_id ?  'yellow' : this.state.backgroundColor)}}></input></li>
</div>
);
}else{
return(
<div key={element._id}>
<li>{element.username}</li>
</div>
);
}
})}
</ul>
</div>
</Modal.Body>
</Modal>
</div>
)
}
}

Issue

您已经正确地使用state来存储"活动id",但是您只使用一个state来表示按钮的值。

<input 
type="button" 
id={element._id} 
onClick={this.handleProductSelect.bind(this, element._id)} 
value={this.state.Input} // <-- same single state for all buttons!
style = {{
backgroundColor: (element._id === this.state.active_id ?  'yellow' : this.state.backgroundColor)
}}
/>
<标题>

解决方案因为我认为目的是保留已经"激活"的按钮,即你想要标签"已请求"。为了保持不变,您应该添加一些状态来存储所有请求的活动id。也不需要在状态中存储静态内容,即按钮标签,与背景颜色相同,这都是基于state.active_id值的派生数据。

this.state = {
active_id: null,
requestedIds: {},
}

handleProductSelect更新为curry箭头函数。箭头函数将类组件的this绑定到回调。curry函数允许您不需要匿名回调函数来附加处理程序

handleProductSelect = id => () => {
this.setState(prevState => ({ 
active_id: prevState.active_id === id ? null : id, // toggle active id
requestedIds: {
...prevState.requestedIds,
[id]: id, // add requested id
},
}));
}

更新Input以检查requestedIds是否有当前元素_id的键,并有条件地呈现按钮标签。同样,检查活动id的背景颜色。

<input 
type="button" 
id={element._id} 
onClick={this.handleProductSelect(element._id)} 
value={this.state.requestedIds[element._id] ? 'Requested' : 'Add Friend'}
style = {{
backgroundColor: (element._id === this.state.active_id ?  'yellow' : 'white')
}}
/>

最新更新