如果这听起来像是一个新问题,我很抱歉。还没找到答案。
我基本上尝试使用类的方法作为 JSX 中 onClick 的回调。
这是我的应用程序组件的代码:
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
constructor(props) {
super(props);
this.deletePost = this.deletePost.bind(this);
}
deletePost() {
// this.props.posts = this.props.posts.splice(i,1)
console.log("Deleted the post");
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to learn React</h1>
</header>
<div>
<input type="text"/>
<button>Post</button>
</div>
<br/>
<div className="post-list">
<hr/>
{this.props.posts.map(function(post, i){
return <div>
{post} - {i}
<button onClick={this.deletePost}>Del</button>
<hr/>
</div>;
})}
</div>
</div>
);
}
}
App.propTypes = {
posts: PropTypes.array
};
export default App;
我得到的错误如下:
TypeError: Cannot read property 'deletePost' of undefined
(anonymous function)
src/components/App.js:34
31 | {this.props.posts.map(function(post, i){
32 | return <div>
33 | {post} - {i}
> 34 | <button onClick={this.deletePost}>Del</button>
35 | <hr/>
36 | </div>;
37 | })}
所以我的问题是如何将deletePost函数传递给onClick?
最佳答案
问题是 this
在映射函数回调中未定义。你可以使用 arrow functions ?你有必要的转译吗?如果是,使用箭头函数可以解决这个问题:
{this.props.posts.map((post, i) => { // <-- arrow function
return <div>
{post} - {i}
<button onClick={this.deletePost}>Del</button>
<hr/>
</div>;
})}
如果你不能或不想在那里使用箭头功能,你可以这样做:
render() {
const deletePost = this.deletePost; // Save variable while we have access to this
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to learn React</h1>
</header>
<div>
<input type="text"/>
<button>Post</button>
</div>
<br/>
<div className="post-list">
<hr/>
{this.props.posts.map(function(post, i){
return <div>
{post} - {i}
<button onClick={deletePost}>Del</button>
<hr/>
</div>;
})}
</div>
</div>
);
}
关于javascript - 无法从 ReactJS 的 render 方法中将类方法传递给 onClick ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48824461/