0

我刚开始过渡到 React Native 中的 Hooks,我很难将数据传递给子元素。使用基于类的组件,我们可以进行非常简单的 XML 样式的 props 传递。

类示例

class Parent extends React.Component {
    render() {
        return (
            <Child data={"Hello"}/>
        )
    }
}

还有孩子:

class Child extends React.Component {
    render() {
        return (
            <Text>{this.props.data}</Text>
        )
    }
}

使用 Hooks 的示例:

使用钩子时,我能够通过以下方式传递数据:

<Child {...["Hello"]} />

钩子看起来像:

export const Child = (data) => {
    return (
        <Text>{data[0]}</Text>
    )
}

有没有办法只将子类重构为钩子并保持对这些元素的调用不变(<Child data={"Hello"}/>)?

4

2 回答 2

2

我想如果你离开<Child data={"Hello"}/>你的父组件并使用钩子重构Child组件,你可以像下面这样访问数据:

export const Child = ({data}) => {
   return (
      <Text>{data}</Text>
   )
}

从技术上讲props,已作为const Child = (props) => {}. 一旦你解构props,你就可以拥有data上面的属性。

这称为对象解构,请在此处进一步阅读。

我希望这会有所帮助!

于 2019-12-11T09:23:30.723 回答
1

你只是错过了一小步:

export const Child = (data) => {... 

应该:

export const Child = (props) => {... 
  const {data} = props

或者:

export const Child = ({data}) => {..
于 2019-12-11T09:24:23.383 回答