- 父组件给子组件传值(props)------子组件执行父组件里的属性及方法
父组件:
import React from 'react';
import ChildNews from './ChildNews'
class News extends React.Component {
constructor(props) {
super(props);
this.state = {
news:[
{
id:"1",
title:"React 框架"
},
{
id:"2",
title:"Vue 框架"
},
{
id:"3",
title:"JavaScript 框架"
},
{
id:"4",
title:"Bootstrap 框架"
}
]
};
}
sendMsg(index){
console.log(index);
}
render() {
return (
<div>
我是父组件
<hr/>
{
this.state.news.map((v,k)=>{
return(
<ChildNews key={k} method={this.sendMsg.bind(this,k)} id={v.id} title={v.title}/>
)
})
}
</div>
);
}
}
export default News;
子组件:
import React from 'react';
class ChildNews extends React.Component {
constructor(props) {
super(props);
this.state = { };
}
//子组件 如何获取父组件里面的方法
getNewsMsg=()=>{
this.props.method();
}
render() {
return (
<div>
<span>{this.props.id}</span>
<span>{this.props.title}</span>
<button onClick={this.getNewsMsg}>执行父组件的方法</button>
</div>
);
}
}
export default ChildNews;
总结:父组件给子组件传值,可以传值,传方法,传整个组件都可以,在子组件里面实现父组件的方法,属性的执行和调用。
- 子组件给父组件传值------子组件获取父组件整个对象
- 可以借助父组件传方法给子组件,子组件调用方法传参,到父组件的方法当中。
父组件:
import React from 'react';
import ChildNews from './ChildNews'
class News extends React.Component {
constructor(props) {
super(props);
this.state = {
news:[
{
id:"1",
title:"React 框架"
},
{
id:"2",
title:"Vue 框架"
},
{
id:"3",
title:"JavaScript 框架"
},
{
id:"4",
title:"Bootstrap 框架"
}
]
};
}
render() {
return (
<div>
{
this.state.news.map((v,k)=>{
return(
<ChildNews key={k} obj={this} id={v.id} title={v.title}/>
)
})
}
</div>
);
}
}
export default News;
子组件:
import React from 'react';
class ChildNews extends React.Component {
constructor(props) {
super(props);
this.state = { };
}
//子组件获取父组件整个对象
getParent=()=>{
console.log(this.props.obj);
}
render() {
return (
<div>
<button onClick={this.getParent}>获取父组件整个对象</button>
</div>
);
}
}
export default ChildNews;
- 父组件直接获取子组件对象
- 在父组件中的子组件上定义ref属性,通过 this.refs属性或方法
父组件:
import React from 'react';
import ChildNews from './ChildNews'
class News extends React.Component {
constructor(props) {
super(props);
this.state = {
news:[
{
id:"1",
title:"React 框架"
},
{
id:"2",
title:"Vue 框架"
},
{
id:"3",
title:"JavaScript 框架"
},
{
id:"4",
title:"Bootstrap 框架"
}
]
};
}
getChild=()=>{
//通过ref获取
let info=this.refs.newsinfo;
console.log(info);
}
render() {
return (
<div>
{
this.state.news.map((v,k)=>{
return(
<ChildNews ref="newsinfo" key={k} id={v.id} title={v.title}/>
)
})
}
<button onClick={this.getChild}>获取子组件</button>
</div>
);
}
}
export default News;
- 父组件给子组件传值
-
defaultProps:父组件传值中,若父组件调用子组件不传值,可以在子组件中使用defaultProps定义默认的值
-
propTypes:验证传值的合法性
使用之前先安装:cnpm install prop-types --save
两个均给子组件使用:
import React from 'react';
//子组件中传值进行约束
import PropTypes from 'prop-types';
class ChildNews extends React.Component {
render() {
return (
<div>
<span>{this.props.id}</span>
<span>{this.props.title}</span>
</div>
);
}
}
//定义传值的默认
ChildNews.defaultProps={
id:"1",
title:"我是默认"
}
//约束传值的类型
ChildNews.propTypes={
id:PropTypes.string,
title:PropTypes.string
}
export default ChildNews;