React中组件的传值

2020-12-24  本文已影响0人  肾仔博

1、类组件--父传子

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

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、子组件传递父组件

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
        })
    }
}

上一篇 下一篇

猜你喜欢

热点阅读