【问题标题】:Is there a way to not pass anything to a child prop method?有没有办法不将任何东西传递给子道具方法?
【发布时间】:2019-10-15 22:50:30
【问题描述】:

错误:TypeError:_this.props.handleChange 不是函数

我有一个 React 组件,它有一个用于另一个视图组件的 prop 方法。

问题是我的其他视图组件需要使用我的 Child 组件但是它会导致错误,因为它需要使用 prop 方法。

class NeedsPropMethod extends Component {
 handleChange = value => {
  // receives the value
 }

 return (
  <Child toy="car" color="blue" handleChange={this.handleChange}>
 )
}

class DoesntNeedPropMethod extends Component {
 return (
  <Child toy="car" color="blue"}>
 )
}

class Child extends Component {
 return (
  this.props.toy; // "car"
  this.props.color; // "blue"
  this.props.handleChange(value) // I do not need this but it gives me the error above
 );
}

【问题讨论】:

  • 你没有通过它,如果你不需要它删除它。
  • 您上面的Child 类有语法错误。 真正应该是什么样子?
  • 你可以添加一个布尔检查,如果为真,返回handlechange,否则不要运行
  • 我希望我可以,但是 prop 方法正在我的其他视图组件中使用,所以我试图找出一种使其可重用或类似的方法。将在我的示例中添加更多代码。

标签: javascript node.js reactjs ecmascript-6 single-page-application


【解决方案1】:

您可以像这样将 propTypes 添加到您的代码中,使其成为可选

Child.propTypes = {
  handleChange: PropTypes.func
};

所以你的 handleChange 将是可选的

【讨论】:

  • 是的。我相信这是通往它的道路。我仍然遇到错误“TypeError: _this.props.handleChange is not a function”。
  • 你在哪里使用 propTypes 吗?
  • 仅用于子组件
  • 向我展示您的具有 propTypes 的 ChildComponent 的完整代码
  • 如果prop方法存在,我只需要添加一个if语句
【解决方案2】:

来自 Tony Ngo 的回答

Child.propTypes = {
  handleChange: PropTypes.func
};

那么你只需要检查是否使用了prop方法

if (this.props.handleChange) {
 // do stuff here
}

【讨论】:

  • 你可以添加deafult props 而不必这样做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 1970-01-01
  • 2016-08-23
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多