简体   繁体   中英

How to destructure props to pass for childs component? REACT-NATIVE

I created a prop object with all the necessary props to be passed to the childs component from the parent component, but it looks a little messy:

 render() {
    
    const props = {
        tracks: this.state.tracks, //this props is used to print the list 
        info_track: (this.state.random) ? this.state.random_tracks : this.state.tracks, //this props is used to set the queue either shuffle is active or not
        playing: this.state.playing,
        play_selected_music: this.play_selected_music.bind(this),
        get_time: this.get_time.bind(this),
        play: this.play_music.bind(this),
        pause: this.pause.bind(this),
        shuffle: this.shuffle.bind(this),
        next_song: this.next_song.bind(this),
        previous_song: this.previous_song.bind(this),
    }

    return (
        <>
            <Tracks {...props}></Tracks>
        </>
    )
}

as you can see I created the prop object, then in the child component I can use them, they told me that I can destructure this to look a little bit better, but to be honest dont know how to destructure this with validations and binding functions, all the examples are using pure objects:

person: {
 nombre: "hi",
 surname: "bye",
 
}

so the destructure will be:

const {nombre, surname} = person

but dont know how will be in my case, thanks:)

const Tracks = ({tracks, info_track, //...and all other props you have}) => {
  // then just use them here
  return <Text>{info_track}</Text>
}

Or if you using class base component

class Tracks extends Components {
   render(){
    const {tracks,info_track,...} = this.props

    return <Text>{info_track}</Text>
  }
}

to de-structuring props which is comes from parent component to child component, it is easy. based on your case, your child component Name is Tracks .

//Method 1:
export const Tracks = ({
  tracks,
  info_track,
  playing,
  play_selected_music,
  ...restProps
}) => {


  // return your components.. 

}

//Method 2
export const Tracks = () => {
  const {
    tracks,
    info_track,
    playing,
    play_selected_music,
    get_time,
    play,
    ...restProps
  } = props

  //return your component
}

//Method 3, if you use class Component.
class Tracks extends Component {
  const {
    tracks,
    info_track,
    playing,
    play_selected_music,
    get_time,
    play,
    ...restProps
  } = this.props

//your component
}

you can replace ...restProps , with the rest of the key that not mentioned yet.

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