一、父组件给子组件传值
- 父组件给子组件传递属性值
- 父组件给子组件传递方法
- 给子组件传递整个父组件对象
父组件 Parent.js
import React,{Component} from "react";
//导入子组件
import Child from "./Child.js"
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
name:"你好!我是父组件",
arr:[
{
id:'1',
title:"Vue框架"
},
{
id:'2',
title:"React框架"
},
{
id:'3',
title:"Bootstrap框架"
},
{
id:'4',
title:"Jquery框架"
},
]
};
}
//给子组件传方法
sedmsg(index){
console.log(index)
}
render() {
return (
// 父组件给子组件传递属性值
// 父组件给子组件传递方法
// 给子组件传递整个父组件对象
<div>
我是父组件
<hr/>
{
this.state.arr.map((value,index)=>{
return(
<Child key={index} obj={this} method={this.sedmsg.bind(this,index)} title={value.title} id={value.id}/>
)
})
}
</div>
);
}
}
export default Parent;
子组件 Child.js
import React,{Component} from "react";
class Child extends Component {
constructor(props) {
super(props);
this.state = { };
}
//接收父组件的方法
getmsg=()=>{
this.props.method()
}
getobj=()=>{
console.log(this.props.obj)
}
render() {
return (
<div>
{/* 接收父组件传的值 */}
<span>{this.props.id}</span>
<span>{this.props.title}</span>
<button onClick={this.getmsg}>接收父组件的方法</button>
<button onClick={this.getobj}>接收父组件整个对象</button>
</div>
);
}
}
export default Child;
二、父组件获取整个子组件
给子组件添加属性ref 在父组件里面直接this.refs.name 可以拿到子组件
import React,{Component} from "react";
//导入子组件
import Child from "./Child.js"
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
name:"你好!我是父组件",
}
//获取子组件对象
getChild=()=>{
console.log(this.refs.children)
}
render() {
return (
<div>
我是父组件
<hr/>
{
this.state.arr.map((value,index)=>{
return(
<Child ref="children"/>
)
})
}
<button onClick={this.getChild}>获取子组件整个对象</button>
</div>
);
}
}
export default Parent;
三、设置子组件的默认值和值的约束
- defaultProps:父组件传值中,如果父组件调用子组件不传值,可以在子组件中使用defaultProps定义默认的值;
- propTypes:验证传值的合法性也就是说给值的约束;
这两个都是给子组件使用的;
使用propTypes 就必须要安装 prop-types
cnpm install prop-types --save
import React,{Component} from "react";
//导入prop-types 传值进行约束
import PropsTypes from 'prop-types'
class Child extends Component {
constructor(props) {
super(props);
this.state = { };
}
//接收父组件的方法
getmsg=()=>{
this.props.method()
}
getobj=()=>{
console.log(this.props.obj)
}
render() {
return (
<div>
{/* 接收父组件传的值 */}
<span>{this.props.id}</span>
<span>{this.props.title}</span>
<button onClick={this.getmsg}>接收父组件的方法</button>
<button onClick={this.getobj}>接收父组件整个对象</button>
</div>
);
}
}
//进行默认
Child.defaultProps={
id:"1",
title:"我是默认"
}
//进行约束 类名.protoTypes 约束PropsTypes.类型
Child.protoTypes={
id:PropsTypes.string,
title:PropsTypes.string,
// isck:PropsTypes.bool,
// ismeth:PropsTypes.func,
// isb:PropsTypes.object
}
export default Child;