bind放在constrctor内,使用该方法时应如何传参
来源:3-3 实现 TodoList 新增删除功能
孙克磊
2019-10-08
我如果将方法的bind放在constrctor内,在li标签中使用handleItemDel方法时候,应如何传参?我此时写法有误,无法得到正确的结果
TodoList.js代码如下
import React, { Component, Fragment } from 'react'
class TodoList extends Component {
constructor (props) {
super(props)
this.handleInputChange = this.handleInputChange.bind(this)
this.handleBtnClick = this.handleBtnClick.bind(this)
this.handleItemDel = this.handleItemDel.bind(this)
this.state = {
inputVale: '',
list: []
}
}
render () {
return (
<Fragment>
<div>
<input
value = { this.state.inputVale }
onChange = { this.handleInputChange }
/>
<button onClick = { this.handleBtnClick }>submit</button>
</div>
<ul>
{
this.state.list.map((item, index) => {
return (
<li key={ index } onClick={ this.handleItemDel(index) }>{ item }</li>
)
})
}
</ul>
</Fragment>
)
}
handleInputChange (e) {
this.setState({
inputVale : e.target.value
})
}
handleBtnClick () {
this.setState({
list: [...this.state.list, this.state.inputVale],
inputVale: ''
})
}
handleItemDel (index) {
console.log(index)
}
}
export default TodoList
2回答
-
onClick={ () => this.handleItemDel(index) }
112019-10-09 -
功夫熊猫77
2019-10-08
import React, { Component, Fragment } from 'react'
class TodoList extends Component {
constructor (props) {
super(props)
this.handleInputChange = this.handleInputChange.bind(this)
this.handleBtnClick = this.handleBtnClick.bind(this)
this.handleItemDel = this.handleItemDel.bind(this)
this.state = {
inputVale: '',
list: []
}
}
render () {
return (
<Fragment>
<div>
<input
value = { this.state.inputVale }
onChange = { this.handleInputChange }
/>
<button onClick = { this.handleBtnClick }>submit</button>
</div>
<ul>
{
this.state.list.map((item, index) => {
return (<li key={ index } onClick={this.handleItemDel}>{ item }</li>)
})
}
</ul>
</Fragment>
)
}
handleInputChange (e) {
this.setState({
inputVale : e.target.value
})
}
handleBtnClick () {
this.setState({
list: [...this.state.list, this.state.inputVale],
inputVale: ''
})
}
handleItemDel (index) {
{/*
const list = [...this.state.list];
list.splice(index,1);
this.setState({
list:list
})
*/}
console.log(index)
}
}
export default TodoList
00
相似问题