1、类组件--父传子
- 父组件通过 属性=值 的形式来传递给子组件数值;
- 子组件通过 props 参数获取父组件传递过来的数值;
import React, { Component } from 'react';
class Children extends Component {
constructor(props) {
super(props);
}
render() {
const {name,age} = this.props;
return (
<h2>子组件展示数据: {name + " " + age}</h2>
)
}
}
export default class App extends Component {
render() {
return (
<div>
<Children name="mike" age="18" /> //显示:子组件展示数据:mike 18
</div>
)
}
}
2、函数组件--父传子
import React, { Component } from 'react'
function Children(props) {
const { name, age } = props;
return (
<h2>{name + " " + age}</h2>
)
}
export default class App extends Component {
render() {
return (
<div>
<Children name="mike" age="18" />
</div>
)
}
}
3、参数propTypes
- 若对项目中的数据进行验证的话,可以通过prop-types库来进行参数验证;
import React, { Component } from 'react'
import PropTypes from 'prop-types';
function Children(props) {
const { name, age } = props;
const { names } = props;
return (
<div>
<h2>{name + " " + age}</h2>
<ul>
{
names.map((item, index) => {
return <li>{item}</li>
})
}
</ul>
</div>
)
}
Children.propTypes = {
name: PropTypes.string,
age: PropTypes.number,
names: PropTypes.array
}
export default class App extends Component {
render() {
return (
<div>
<Children name="mike" age={18} names={["nba", "cba"]} />
</div>
)
}
}
4、子组件传递父组件
- React中同样是通过props传递信息,只是让父组件给子组件传递一个回调函数,在子组件中调用函数即可;
import React, { Component } from 'react'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
render() {
return (
<div>
<h2>当前计数: {this.state.counter}</h2>
<button onClick={e => this.increment()}>+</button>
</div>
)
}
increment(){
this.setState({
counter: this.state.counter + 1
})
}
}