所以我有 li 个具有key属性的元素,我想在我的函数中访问其key属性
我正在尝试类似的事情
deleteTask(event){
event.preventDefault();
console.log(event.currentTarget.parentElement.key.value);
}
但是我不知道如何访问键属性
const temp1 = temp.map( (x,i) => {
return(
<li key={i}>{x}
<button onClick={this.editTask.bind(this)}>Edit</button>
<button onClick=
{this.deleteTask.bind(this)}>Delete</button>
</li>
)
})
我遇到了错误:
TypeError:无法读取未定义的属性“值” Task.deleteTask
答案 0 :(得分:0)
通过传递给函数来尝试
<li key={i}>{x}
<button onClick={this.editTask.bind(this,i)}>Edit</button>
<button onClick={this.deleteTask.bind(this,i)}>Delete</button>
</li>
deleteTask(key){
event.preventDefault();
//You can access key here
console.log(key)
//this works perfectly fine
}
答案 1 :(得分:0)
如何向
const temp1 = temp.map( (x,i) => {
return(
<li key={i} data-key={i}>{x}
<button onClick={this.editTask.bind(this)}>Edit</button>
<button onClick=
{this.deleteTask.bind(this)}>Delete</button>
</li>
)
})
然后:
console.log(event.currentTarget.parentElement.dataset['key']);
答案 2 :(得分:0)
看看这是否对您有用:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: ['a','b','c']
};
this.deleteItem = this.deleteItem.bind(this);
}
deleteItem(index) {
console.log('Deleting task:' + index);
this.setState((prevState) => {
const aux = Array.from(prevState.items);
aux.splice(index,1);
return ({
...prevState,
items: aux
});
});
}
render() {
const listItems = this.state.items.map((item,index) => {
return(
<React.Fragment>
<li key={index}>{item + ' '}
<button onClick={() => this.deleteItem(index)}>X</button>
</li>
</React.Fragment>
);
}
);
return(
<ul>
{listItems}
</ul>
);
}
}
ReactDOM.render(<App/>,document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>