简体   繁体   中英

Pass data to React (Native) hooks like class-based components

I'm just starting transitioning to Hooks in React Native, and I have a hard time passing data to child elements. With class-based components, we could do a very simple XML-style passing of props.

Example with classes

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

And the child:

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

Example with Hooks:

When using a hook, I was able to pass data via:

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

The hook would look like:

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

Is there a way to refactor just the child classes into hooks and leave calls to these elements untouched ( <Child data={"Hello"}/> ) ?

I guess if you leave as <Child data={"Hello"}/> in your parent component and refactoring Child component with hooks, you can access the data just like the following:

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

Technically props has been passed to your component as const Child = (props) => {} . Once you destructure props , you could have the data property as above.

It's called object destructuring, read further here .

I hope that helps!

You are just missing a small step:

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

should be:

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

or:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM