React中的组件: 解决html 标签构建应用的不足。
使用组件的好处:把公共的功能单独抽离成一个文件作为一个组件,哪里里使用哪里引入。
父子组件:组件的相互调用中,我们把调用者称为父组件,被调用者称为子组件
父子组件传值:
父组件给子组件传值
1.在调用子组件的时候定义一个属性 <Header msg='首页'></Header>
2.子组件里面 this.props.msg
说明:父组件不仅可以给子组件传值,还可以给子组件传方法,以及把整个父组件传给子组件。
父组件主动获取子组件的数据
1、调用子组件的时候指定ref的值 <Header ref='header'></Header>
2、通过this.refs.header 获取整个子组件实例
代码:
import React, {Component} from 'react';
class Sonc extends Component {
constructor(props) {
super(props);
this.state = {
msg2:'i am son c',
givefa:'it is sonc ,it will give fatherc'
};
}
render() {
return (
<div>
{/* {this.state.msg}
{this.state.givefa} */}
{/* {this.props.title}
<button onClick={this.props.run}>点击执行父组件的run方法</button>
<button onClick={this.props.allf.getData}>点击执行父组件的run方法</button>
<button onClick={this.props.allf.getChildData.bind(this,'我是子组件的数据')}>点击执行子组件给父组件传值</button> */}
<hr /> 以下是父组件主动获取子组件的数据
</div>
);
}
}
export default Sonc;
代码2:
import React, {Component} from 'react';
import Sonc from './Sonc';
class Fatherc extends Component {
constructor(props) {
super(props);
this.state = {
msg1:'i am fatherc',
title:"it is father's title"
};
}
run=()=>{
alert(" i am run ff of fuzujian")
}
getData=()=>{
alert(this.state.msg1)
}
getChildData=(result)=>{
alert(result);
this.setState({
msg1:result
})
}
getSonc=()=>{
alert(this.refs.sonc.state.msg2)
}
render() {
return (
<div>
{this.state.msg1}
<hr />
{/* <Sonc title={this.state.title} run={this.run} allf={this}/>
{this.state.msg1} */}
<button onClick={this.getSonc}>获取整个底部组件</button>
<Sonc ref='sonc' />
</div>
);
}
}
export default Fatherc;
import React, {Component} from 'react';
import Sonc from './Sonc';
class Fatherc02 extends Component {
constructor(props) {
super(props);
this.state = {
msg1:'i am fatherc02',
title:"it is fatherc02's title"
};
}
render() {
return (
<div>
{this.state.msg1}
<hr />
<Sonc title={this.state.title} />
</div>
);
}
}
export default Fatherc02;