我是React JS的新手,我想在其中进行onclick,但是当我单击按钮上显示this is undefined
时,有人可以帮助我如何解决此错误吗?如果此deleteTask
是否有效,但该函数没有调用,这是我的完整代码
class PalladiumHub extends React.Component {
render() {
return (<tr>
<td>{this.props.name.id}</td>
<td>{this.props.name.name}</td>
<td><button type="button">Edit</button><button onClick={function(e) { this.props.deleteTask(this.props.key) } }>Delete</button></td>
</tr>
)
}
} //{} {}
class CallCRUD extends React.Component {
constructor(props) {
super(props);
this.deleteTask = this.deleteTask.bind(this);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
deleteTask(index) {
alert('sdsd');
console.log(index);
//return false;
let tasks = this.state.items;
tasks.splice(index,1);
this.setState({
items:tasks
})
}
render() {
console.log(this.state.items);
return (<table border="1"> <tr><th>ID</th><th>Name</th><th>Action</th></tr> {
this.state.items.map( (data,index) => {
return <PalladiumHub name={data} key={data.id} deleteTask ={this.deleteTask} />
})
}
</table>
);
}
}
ReactDOM.render(
<CallCRUD />, document.getElementById('root')
);
答案 0 :(得分:2)
不要使用函数,它们会删除shopt -s globstar
for file in ./**/*.mp3; do
some command "$file"
done
绑定
this
将其更改为
onClick={function(e) { this.props.deleteTask(this.props.key) } }
另外,我希望您阅读this
答案 1 :(得分:1)
您好,您需要绑定onClick处理程序。 检出此页面https://reactjs.org/docs/handling-events.html
class PalladiumHub extends React.Component {
onClick = () => {
this.props.deleteTask(this.props.key)
}
render() {
return (<tr>
<td>{this.props.name.id}</td>
<td>{this.props.name.name}</td>
<td><button type="button">Edit</button><button onClick={this.onClick.bind(this)}>Delete</button></td>
</tr>)
}
}