首页 > 解决方案 > 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”?

标签: reactjstypeerrorreact-props

解决方案


如果您尝试将函数从父组件传递到子组件并保持原始上下文,则值得通过以下任一方式将其绑定到该组件:

<SomeComponent someFunction={this.someFunction.bind(this)} />

或者通过像这样声明你的函数:someFunction = args => {}

更深入地了解为什么this2.props.someFunction is not a function,通过像这样向下传递函数,someFunction={(arg) => {this.someFunction(arg)}}您实际上并没有将函数传递给子组件,而是调用函数并返回结果。


推荐阅读