加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在一个组件中定义属性并传递给reactJs中的其他组件?

发布时间:2020-12-15 20:48:45 所属栏目:百科 来源:网络整理
导读:I have a parent component and a child component,I want to pass property from Parent to Child by using {…this.props},I dont want any action or reducer in the picture,Is it possible to do this? 我的孩子组件是这样的: – import React,{ Compo

I have a parent component and a child component,I want to pass
property from Parent to Child by using {…this.props},I dont want
any action or reducer in the picture,Is it possible to do this?

我的孩子组件是这样的: –

import React,{ Component } from 'react'
import ReactDOM from 'react-dom'

 class SampleChild extends Component {
   constructor(props) {
     super(props)
   }
  render(){
    return(
      <div>This is Parent</div>
          )
         }
  }

 SampleChild.propTypes={
        Header:React.PropTypes.string.isRequired
 }
 export default SampleChild

我的父组件是这样的: –

import React,{ Component } from 'react'
import ReactDOM from 'react-dom'

class SampleParent extends Component {
  constructor(props) {
    super(props)
  }

  render(){
      return(
          <div><SampleChild {...this.props}/></div>
      )
  }
}
export default SampleParent

现在我如何将SampleParent组件中的Header属性传递给SampleChild?.请帮助我.

<SampleParent Header="Hello from Parent" />

因为你将所有道具从SampleParent传播到SampleChild,你需要确保SampleParent只是接收它作为支柱,如果它是动态的,那么你会为你做这个技巧.

如果它是静态道具,您可以在DefaultProps中为SampleParent定义它,并且您将始终传递相同的字符串.

SampleParent.defaultProps = {
   Header: 'Hello from Parent'
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读