React组件间信息传递方式?

    互联网/前端 89次点击 · 1184天前 · 徐春丽
如何将PDF文件里的内容快速截图?Excel表格技巧— BETAINV函数使用攻略? 徐春丽

1条回答我要回复

    林教练1184天前

      父传子
      父组件定义一个 name getconstructor(props) {
      super(props)
      this.state = {
      name: "小明",
      get:1
      }
      render() {
      return (
      <div>
      爷爷
      <Fuqin listname="name" listget= "get"/>
      </div>
      );
      }
      }


      子组件通过 this.props 接收render() {
      console.log(this.props)
      let {listname , listget} = this.props
      return (
      <div>
      {listname}
      {listget}
      </div>
      )
      }
      子传父
      先在父组件定义一个方法class app1 extends Component {
      constructor(props) {
      super(props)
      this.state = {
      title: '' "
      }
      this.fn = this.fn.bind(this) // 如果里面有值就在这绑定一下 this
      }
      fn(q){
      console.log(q)
      this.setState ({
      title :'我是老大'
      })

      }
      render() {
      let { fn } = this
      // console.log(fn)

      return (
      <div>
      我是父亲
      {this.state.title}
      //冲这里发送一个收子组件接收
      <Div div = {this.state.title} fn = {fn}/>
      </div>
      )
      }
      }在子组件定义一个事件 接收 父组件的方法class app2 extends Component {
      constructor(props) {
      super(props)
      }
      //fn(){
      // let {fn} = this.props
      // fn()
      //}
      //这种方法多次一举
      render() {
      let {fn} = this.props
      return (
      <div>
      <button OnClick= {() => {fn("我是儿子传过去的")}}>我是儿子</button>
      </div>
      )
      }
      }
      跨组件传
      先下载npm install prop-types -S 在爷爷组件import PropTypes from 'prop-types'
      class Index extends Component {
      constructor(props) {
      super(props)
      }
      // 第一步:父组件提供一个函数,用来返回相应的context的对象
      getChildContext() {
      return {
      name: '熊大',
      like: '睡觉'
      }
      }
      render() {
      let { username, like } = this.props
      return (
      <div>
      我是爷爷组件
      <List listUserName={ username } listLike={ like } />
      </div>
      )
      }
      }

      // 第二步:父组件声明自己支持的context,并提供context中属性的校验
      yeye.childCOntextTypes= {
      name: PropTypes.string,
      like: PropTypes.string
      }儿子组件import PropTypes from 'prop-types'
      class erzi extends Component {
      constructor(props) {
      super(props)
      }
      render() {
      console.log(this.context)
      let { name, get } = this.context
      return (
      <div>
      儿子组件
      {name}
      {get}
      </div>
      );
      }
      }
      // 第三步: 跨组件需要声明自己需要使用的context,并校验
      erzi.cOntextTypes= {
      name : PropTypes.string,
      get:PropTypes.string
      }

       

    请先登录后,再回复