react的组件传值

简单的说一下父传子(属性传值)

1.一般而言,我们用的是ES6中的class类来书写

import React, {Component} from 'react';

class Abc extends Component {
    constructor(props) {
        super(props);
        
    }

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

export default Abc;

2.在父组件中

import React, {Component} from 'react';
import Abc from "../to/abc";  //---<引入子文件
class App extends Component {
    constructor(props) {
        super(props);
        this.state={
            aa:"hello react"  //--->初始化
        }
    }

    render() {
        return (
            <div>
                <Abc cd={this.state.aa} ac="我是父组件给子组件传的值"> </Abc>
            </div>
        );
    }
}

export default App;

3.在子组件中(abc.js)

import React, {Component} from 'react';

class Abc extends Component {
    constructor(props) {
        super(props);

    }

    render() {
        return (
            <div>
                <p>{this.props.ac}</p> //--->我是父组件给子组件传的值
                <p>{this.props.cd}</p>   //--->hello react
            </div>
        );
    }
}

export default Abc;

子组件给父组件传递值

1.要先在子组件中定义一个方法,通过方法的参数,将值传递给父组件

import React, {Component} from 'react';

class Abc extends Component {
    constructor(props) {
        super(props);

    }
    tag(){
        this.props.tag1("我是子组件传递给父组件的值");//--->tag1是父组件的变量名
    }
    render() {
        return (
            <div>
                <p>{this.props.ac}</p>
                <p>{this.props.cd}</p>
                                          {/* bind是改变this的指向,也可以用箭头函数改变*/}
                <button onClick={this.tag.bind(this)}>点击切换父组件的内容</button>
            </div>
        );
    }
}

export default Abc;

2.在父组件中

import React, {Component} from 'react';
import To from "../to/to";
import List from "../to/list";
import Abc from "../to/abc";
class App extends Component {
 constructor(props) {
     super(props);
     this.state={
         aa:"hello react"
     }
 }
 ch(q){
     alert(q);//--->q就是子组件传递过来的内容
     this.setState({aa:q});//--->在更新当前的aa的内容
 }
 render() {
     return (
         <div>
             <Abc cd={this.state.aa} ac="我是父组件给子组件传的值"
             tag1={this.ch.bind(this)}> </Abc>
         </div>
     );
 }
}

export default App;

兄弟传值

就是把父传子,子传父结合到了一起,通过子组件(定义一个方法,通过方法的参数),将值传递到父组件,在通过父组件(属性传值),传递给另一个子组件

不过后面会有redux,react-redux传值,会方便很多

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,526评论 1 33
  • 2018-08-02更新: 不难想象,这时候联系两个页面的纽带就是URL值或共同的父组件。这就引发了两个解决方法:...
    lavi呀阅读 11,517评论 0 8
  • 包含 react基础 react传值 react路由 和redux管理 和react-redux reactDom...
    栀璃鸢年_49a3阅读 1,142评论 0 1
  • 一根飘忽不定的木桩,紫藤萝又如何敢寄托信任依附而存。 如果一棵紫藤萝愿意拿自己的一生跟木桩做赌注,希望木桩不要让她...
    紫云凝香阅读 291评论 0 0
  • 手机上有各种软件可以记录你一天的运动量,走了多少步,消耗了多少热量,在朋友圈里排第几名,等等。其实,我们更需要能够...
    vivi要学习阅读 194评论 0 0