A:父组件向子组件传值:(通过属性的方式)
import React from "react";
class ChildCpn extends React.Component {
render(){
const {name, age, height} = this.props;
return (
<h2>子组件展示数据: {name + '' + age + " " + height}</h2>
)
}
}
export default class App extends React.Component {
render() {
return (
<div>
<ChildCpn name="why" age="18" height="1.88"></ChildCpn>
</div>
)
}
}
B:父组件向子组件(函数组件)传值
import React from "react";
function ChildCpn(props) {
const {name, age, height} = props;
return (
<h2>子组件展示数据: {name + '' + age + " " + height}</h2>
)
}
export default class App extends React.Component {
render() {
return (
<div>
<ChildCpn name="why" age="18" height="1.88"></ChildCpn>
</div>
)
}
}
C:在父传子的过程中,要明白传的什么类型。。。
1:引入'prop-types库
2:用子组件.PropTypes进行验证。如果不是想要的类型,会报出警告
3:你还可以设置默认值:子组件.defaultProps.如果父元素没有传入。那么显示的是你的默认值。。。
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function ChildCpn(props) {
const { name, age, height } = props;
console.log(name, age, height);
const { names } = props;
return (
<div>
<h2>{name + age + height}</h2>
<ul>
{
names.map((item, index) => {
return <li>{item}</li>
})
}
</ul>
</div>
)
}
class ChildCpn2 extends Component {
// es6中的class fields写法
static propTypes = {
}
static defaultProps = {
}
}
ChildCpn.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
height: PropTypes.number,
names: PropTypes.array
}
ChildCpn.defaultProps = {
name: "why",
age: 30,
height: 1.98,
names: ["aaa", "bbb"]
}
export default class App extends Component {
render() {
return (
<div>
<ChildCpn name="why" age={18} height={1.88} names={["abc", "cba"]}/>
<ChildCpn name="kobe" age={40} height={1.98} names={["nba", "mba"]}/>
<ChildCpn/>
</div>
)
}
}
D:对于父组件的方法,要想使子组件使用。必须传过去(<CounterButton des={e => this.increment()}></CounterButton>)
import React from "react";
class CounterButton extends React.Component {
render() {
const {des} = this.props;
return <button onClick={des}>+1</button>
}
}
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
counter: 0
}
}
render(){
return(
<div>
<h2>当前计数: {this.state.counter}</h2>
<button onClick={e => this.increment()}>+</button>
<CounterButton des={e => this.increment()}></CounterButton>
</div>
)
}
increment() {
this.setState({
counter: this.state.counter + 1
})
}
}