【发布时间】:2020-01-03 04:38:33
【问题描述】:
React passing parameter with arrow function in child component
通过该反馈,我可以了解更新状态的情况。
但是,尽管代码看起来完全相同,但我的代码似乎无法正常工作。
constructor(props) {
super(props);
// this.state = {
// selectedId: 0
// }
this.state = {
selectedId: 0
}
}
handleClick = (id) => {
// const { name, value } = event.target;
console.log(id);
this.setState = ({
selectedId: id
})
}
render () {
//const { isEditClicked } = this.state;
const { selectedId } = this.state;
return (
<div className='admin-match-item'>
{selectedId}
<CustomIconButton type='edit' id={this.props.id} handleClick={this.handleClick} />
</div>
);
}
}
子组件如下所示
//Need refactoring
const CustomIconButton = ({ type, id, handleClick, ...otherProps }) => (
<div>
hi{id}
<button className='button-icon' onClick={() => handleClick(id)}>
{
type == 'add' ? <AddIcon className='icon' /> :
type == 'save' ? <SaveIcon className='icon'/> :
type == 'edit' ? <EditIcon className='icon' /> :
type == 'delete' ? <DeleteIcon className='icon' /> :
<ErrorIcon className='icon' />
}
</button></div>
)
export default CustomIconButton;
我将 props.id 传递给子组件,并使用我单击的 id 更新状态。 console.log 里面的东西正在返回我想要的值,但它不会更新 selectedId 状态(始终为 0) 谁能帮我解决这个问题?
【问题讨论】:
标签: javascript reactjs