我正在尝试根据道具更新 onClick 事件处理程序中的状态。在 console.log 我得到空字符串作为初始状态值。
我已经尝试将组件更改为使用状态挂钩而不是状态来运行。我尝试使用方法在调用 onClick 时更新状态。我已经尝试在类似问题的答案中使用这些建议,这种情况有所不同,可能是因为我在事件处理程序中使用了 setState。
有人知道这里有什么问题吗?提前致谢!
class DropDownItem extends Component {
constructor(props) {
super(props)
this.state = {
selectedItem : ""
}
this.updateItem = this.updateItem.bind(this)
}
updateItem (item) {
this.setState({selectedItem : item})
}
render(){
return (
<div>
<DropdownItem onClick={() => {
this.updateItem(this.props.product)
console.log("item",this.state.selectedItem)
}}
>{this.props.product}</DropdownItem>
<DropdownItem divider/>
</div>
)
}
}
这是父组件的主体:
render() {
const productItems = this.state.products.map((productValue,index) => {
return(<DropDownItem key={index} product={productValue.name} />)
})
return (
<div>
{this.state.products[0] && Array.isArray(this.state.products) ?
<div>
<DropdownComponent
isOpen={this.state.dropdownOpen}
toggle={this.toggle}
product={productItems}
/>
</div> :
<div>loading...</div>}
</div>
)}
我想更新状态以便向用户显示单击的下拉项。
您应该在作为第二个参数提供的回调中获取更新的状态setState
,如下所示
class DropDownItem extends Component {
constructor(props) {
super(props)
this.state = {
selectedItem : ""
}
this.updateItem = this.updateItem.bind(this)
}
updateItem (item, callback) {
this.setState({selectedItem : item}, callback)
}
render(){
return (
<div>
<DropdownItem onClick={() => {
this.updateItem(this.props.product, ()=>{
console.log("item",this.state.selectedItem)
})
}}
>{this.props.product}</DropdownItem>
<DropdownItem divider/>
</div>
)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句