关注互联网应用及运维技术的个人博客

React组件传值

父组件向子组件传值
  1. 通过父组件的props属性向子组件传值

子组件:Children.js

import React, { Component } from 'react';
export default class Children extends Component {
    constructor(props) {
        super(props)
        this.state = {
            name: '',
        }
    }
    render() {
        return (
            <div>
                {this.props.parent}
            </div>
        )
    }
}

父组件:Parent.js

import React, { Component } from 'react'
import Children from './Children'

export default class Parent extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: "父组件内容"
        }
    }
    render() {
        return (
            <div>
                <Children parent={this.state.data} />
            </div>
        )
    }
}
  1. 通过context进行传值
子组件:
import React from 'react'
import PropTypes from 'prop-types'

class ChildComponent extends React.Component {
  // 声明需要使用的Context属性
  static contextTypes = {
    propA: PropTypes.string
  }
  
  render () {
    const {
      propA,
      methodA
    } = this.context
    
    console.log(`context.propA = ${propA}`)  // context.propA = propA
    console.log(`context.methodA = ${methodA}`)  // context.methodA = undefined
    
    return <div>
        
    </div>
  }
}

export default ChildComponent

父组件:
import React from 'react'
import PropTypes from 'prop-types'
import ChildComponent from "./Children_children"
class MiddleComponent extends React.Component {
  render () {
    return <ChildComponent />
  }
}

class ParentComponent extends React.Component {
  // 声明Context对象属性
  static childContextTypes = {
    propA: PropTypes.string,
    methodA: PropTypes.func
  }
  
  // 返回Context对象,方法名是约定好的
  getChildContext () {
    return {
      propA: 'propA',
      methodA: () => 'methodA'
    }
  }
  
  render () {
    return <MiddleComponent />
  }
}

export default ParentComponent
子组件向父组件传值

子组件:

import React, { Component } from 'react';
export default class Children extends Component {
    constructor(props) {
        super(props)
        this.state = {
            name: '',
        }
    }
    render() {
        return (
            <div>
                这是父组件传值内容:{this.props.parent}
                <br />
                <input type="text" onChange={e => { this.props.hanldeChange(e.target.value) }} />
            </div>
        )
    }
}

父组件:

import React, { Component } from 'react'
import Children from './Children'

export default class Parent extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: "父组件内容",
            text: ""
        }
    }
    handleChange(text) {
        this.setState({
            data: text
        })
    }
    render() {
        return (
            <div>
                <p>这是子组件传过来的内容:{this.state.text}</p>
                <Children parent={this.state.data} hanldeChange={this.handleChange.bind(this)} />
            </div>
        )
    }
}

父组件定义的handleChange函数,通过props属性传给子组件。子组件接收并执行handleChange函数,实现子组件向父组件传值。

跨组件传值

使用context实现跨组件传值(当结构复杂时,全局变量不利于追溯数据的源头,会导致应用混乱,不易于维护)

使用场景:是全局性的信息,如用户信息,界面颜色和主题等等。

import React, { Component } from "react";
import PropTypes from "prop-types";
//子(孙)组件
class Button extends React.Component {
  render() {
    console.log(this.context)
    return (
      <div>
        <button style={{ background: this.context.color }}>
          {this.props.children}
        </button>
        <p>{this.context.text}</p>
      </div>
    );
  }
}
//声明contextTypes用于访问MessageList中定义的数据
Button.contextTypes = {
  color: PropTypes.string,
  text:PropTypes.string
};

//子组件
class Message extends React.Component {
  render() {
    return (
      <div>
        <Button>Delete</Button>
      </div>
    );
  }
}
//父组件
class MessageList extends React.Component {
  // 定义Context需要实现的方法
  getChildContext() {
    return {
      color: "red",
      text: "跨组件传值"
    };
  }

  render() {
    return <Message />;
  }
}

// 声明Context类型
MessageList.childContextTypes = {
  color: PropTypes.string,
  text: PropTypes.string
};
class App extends Component {
  render() {
    return <div>
      <MessageList />
    </div>
  }
}
export default App

赞(0)
未经允许不得转载:飞天狒狒 » React组件传值

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址