React 入门及组件之间传值

       最近,有一个很火的前端框架--React,可谓万众瞩目。它的前身是FaceBook的内部项目,最后完善开源,贡献巨大,致敬。另外,国内淘宝基于react开源了ant design,功劳也不小,具体可参考Ant Design的官网:https://ant.design/docs/react/introduce。直奔主题,下面结合个人使用经验及网上查阅的一些资料,对其做简要介绍。希望对初学者有所帮助。

一、组件之间相互传值

1.子组件向父组件传值

 
//子组件
var ChildComment = React.createClass({
	getInitialState: function () {
       return {count:0};
    },
	//点击传值给父组件
	sendTimes: function () {
		var newCount = this.state.count + 1;
		this.setState({ count:newCount });
		//通过props调用父组件的方法
		this.props.getClickCount(newCount);
	},
   render: function () {
	   return (
			<button  onClick={this.sendTimes}>{this.props.buttonName}</button>
	   );
   }
});

//父组件
var ParentComponent = React.createClass({
	getInitialState: function () {
		return {sendCount:0};
	},
	getClickCount: function (newCount) {
		this.setState({sendCount:newCount});
	},
	render: function () {
		return (
			<div>
				<ChildComment getClickCount={this.getClickCount} buttonName="点我有惊喜"/>
				<p>
					共点击{this.state.sendCount}次!
				</p>
			</div>
		);
	}
});
 
2.父组件向子组件传值
//父组件
var ParentComponent = React.createClass({
        getInitialState: function () {
            return {sendCount:0};
        },
        //通过refs方式调用子组件的方法
        sendTimes: function () {
            this.refs.getCountButton.sendCountFunc();
        },
        getSendCount: function () {
            //通过refs方式调用子组件的属性
            this.setState({sendCount:this.refs.getCountButton.state.count + 1});
        },
        render: function () {
            return (
                <div>
                    //定义ref属性且值必须唯一
                    <ChildComment ref="getCountButton" getSendCount={this.getSendCount} buttonName="点我有惊喜"/>
                    <button onClick={this.sendTimes}>父组件调用子组件</button>
                    <p>
                        共点击{this.state.sendCount}次!
                    </p>
                </div>
            );
        }
});

//子组件
var ChildComment = React.createClass({
		getInitialState: function () {
            return {count:0};
        },
        //点击调用
        sendCountFunc: function () {
            var newCount = this.state.count + 1;
            this.setState({ count:newCount });
            //通过props调用父组件的方法
            this.props.getSendCount(newCount );
        },
       render: function () {
           return (
                <button  onClick={this.sendCountFunc}>{this.props.buttonName}</button>
           );
       }
});
 二、类似于get方式传参        JS中我们常常用get方式传参,如:http://www.baidu.com?param=123&type=3,在react中也可以如此传值,那接收页面如何取值呢?看下面:
let query = this.props.location.query;
let param= query.param;
let type = query.type;
 
       如上,可取出传递的参数。React还有一些基本应用,待后续追加介绍。

    

猜你喜欢

转载自1349469499.iteye.com/blog/2317172