reactjs - 是否可以从组件功能中调用操作?
问题描述
我有疑问是否有可能从函数或事件处理程序调用操作?我使用 React-Redux。
例子:
export class Page extends React.Component {
onSomething() {
this.props.onAdd();
};
render() {
return (
<div>
<List
SomeMethod={this.onSomething};
/>
</div>
);
}
}
Page.propTypes = {
onAdd: PropTypes.func,
};
export function mapDispatchToProps(dispatch) {
return {
onAdd: evt => {
dispatch(fetchAdd());
},
};
}
const withConnect = connect(
mapStateToProps,
mapDispatchToProps,
);
const withReducer = injectReducer({ key: 'page', reducer });
const withSaga = injectSaga({ key: 'page', saga });
export default compose(
withReducer,
withSaga,
withConnect,
)(Page);
我收到错误,即:Uncaught TypeError: Cannot read property 'onAdd' of undefined
也许有人知道我做错了什么?
解决方案
您只是缺少函数this
中的上下文。onSomething
您可以在构造函数中、通过类属性或作为 jsx 中的箭头函数绑定它
export class Page extends React.Component {
constructor() {
this.onSomething = this.onSomething.bind(this);
}
// ...
};
或类属性(需要 babel-plugin)
export class Page extends React.Component {
onSomething = () => {
this.props.onAdd();
}
// ...
};
或通过 JSX 中的箭头函数
render() {
return (
<div>
<List
SomeMethod={() => this.onSomething()};
/>
</div>
);
}
推荐阅读
- c# - 从正常的 try/catch 中抛出自定义异常
- c# - 按季度的周分组日期
- android - 如何阻止子 Linearlayout 与父 Linearlayout 圆角重叠?
- java - HMS核心地图套件,地图加载但不渲染
- c++ - 为什么即使使用 -L 和 -I 命令,目标文件也没有与 allegro 库链接?
- laravel - 为什么不能在 laravel 7 中创建新的 vue 组件?
- java - 无法连接到 Solace
- javascript - 如何将节点 js(commonjs) 中的变量导出到普通 javascript(vanilla js)?
- ruby-on-rails - 使用 find_by 加载 Ruby on Rails
- node.js - 请求 url 显示无效的 api