繁体   English   中英

如何解构道具以传递给子组件? REACT-NATIVE

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

我创建了一个道具 object ,其中包含要从父组件传递给子组件的所有必要道具,但它看起来有点乱:

 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>
        </>
    )
}

如您所见,我创建了道具 object,然后在子组件中我可以使用它们,他们告诉我可以解构它以使其看起来更好一些,但老实说不知道如何使用验证和绑定函数来解构它,所有示例都使用纯对象:

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

所以解构将是:

const {nombre, surname} = person

但不知道我的情况如何,谢谢:)

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

或者,如果您使用 class 基本组件

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

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

将来自父组件的道具解构到子组件,这很容易。 根据您的情况,您的子组件 Name 是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
}

您可以用尚未提及的密钥的 rest 替换...restProps

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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