reactjs - TypeError: _this2.props.someFunciton 不是函数 - 反应
问题描述
虽然有类似标题的帖子,但它们都无关紧要或不回答发布的问题。
我在另一个页面中有一个这样调用的组件:
<SomeComponent aParticularProp={(arg) => {this.someFunction(arg)}} />
这是 SomeComponent 的简化版本:
class SomeComponent extends React.Component{
constructor(props){
super(props);
this.state = {someState: "test"};
}
something(){
return (
<SpecialButton
onClick={() => {this.props.someFunction(this.state.someState)}}
/>
)
}
render () {
return (
{this.something()}
);
}
}
为什么我收到“TypeError: _this2.props.someFunciton is not a function”?
解决方案
如果您尝试将函数从父组件传递到子组件并保持原始上下文,则值得通过以下任一方式将其绑定到该组件:
<SomeComponent someFunction={this.someFunction.bind(this)} />
或者通过像这样声明你的函数:someFunction = args => {}
更深入地了解为什么this2.props.someFunction is not a function
,通过像这样向下传递函数,someFunction={(arg) => {this.someFunction(arg)}}
您实际上并没有将函数传递给子组件,而是调用函数并返回结果。
推荐阅读
- mysql - 错误:MySQL 意外关闭。这可能是由于端口阻塞、缺少依赖项、权限不正确、崩溃或关闭
- flutter - Flutter/Dart - 抛出异常时重定向屏幕的按钮?
- python - 如何永远运行 2 个异步函数?
- r - 使用 unz() 将 SAS 数据集读入 R
- c# - 如何在 2D 统一中创建自己的动画?我的意思是,例如,颜色、位置等的变化?
- reactjs - 如何在 Typescript 中将 Promise 合并为一个 Promise
- python - Django:如何为这个 Django 查询集进行自定义排序?
- python - pyglet 中的命名形状
- python - opencv 显示带有边界框和标签的渲染图像
- ruby-on-rails - Rails 关联在哪里 - 为什么不检查类?