【问题标题】:Convert const to class in React Native?在 React Native 中将 const 转换为类?
【发布时间】:2017-05-28 06:24:02
【问题描述】:

我在 React Native 应用中有以下功能

const GreenWood = ({x,y,z,f1,f2, f3}) => {
  ...
}

我需要将其转换为类

class GreenWood extends Component {
  constructor(props) {
      super(props);
  }
  ...
}

但是我的道具 x, y, x 是未定义的。如何推动转发?

【问题讨论】:

  • 我可以建议阅读以下guidethis possible related question 并查看mapDispatchToProps 吗?
  • 好吧,我阅读了该指南,它描述了我试图摆脱的“功能性”方式,但不是我需要的方式。另外,我没有使用 Redux,只是创建组件并想转发一些道具。在其他语言中,这通常在构造函数中完成。

标签: javascript class react-native


【解决方案1】:

我不认为你可以解构类的道具。您必须在所有这些变量之前添加 this.props,或者在您使用它的方法中添加:

var { x, y, z, f1, f2, f3 } = this.props

或者只是把你正在使用的那些放在那个方法中。

【讨论】:

  • 在构造函数中的 super 之后可以这样做吗?我试图这样做。x = props.x;但没有成功
  • 你可以这样做this.x = this.props.x,因为你转换成class你必须把'this'放在props前面。
【解决方案2】:

我猜你有一个函数组件 GreenWood 会返回一些 JSX。

class Greenwood extends React.Component {
  constructor(props) {
   super(props)
   //...whatever construction you need
  }
  render() {
   const { x, y, z, f1, f2, f3 } = this.props
   return // your JSX Here
  }
}

【讨论】:

    猜你喜欢
    • 2020-05-25
    • 2019-05-27
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 2019-04-30
    • 1970-01-01
    • 2019-03-15
    相关资源
    最近更新 更多