react父子传值

前端 0 294 0
发表于: 2020-10-14 21:19:59

简介: 暂无~

父传子

类组件

import React, { Component } from 'react';


// 子组件
class ChildCpn extends Component {
  // 如果只是下面的形式,可以省略
  // constructor(props) {
  //   super(props);
  // }

  render() {
    const { name, age, height } = this.props;
    return (
      <h2>子组件展示数据: {name + " " + age + " " + height}</h2>
    )
  }
}

// 父组件
export default class App extends Component {
  render() {
    return (
      <div>
        <ChildCpn name="hss" age="21" height="1.7" />
        <ChildCpn name="kobe" age="40" height="1.98" />
      </div>
    )
  }
}

函数组件

import React, { Component } from 'react';

// 子组件
function ChildCpn(props) {
  const { name, age, height } = props;

  return (
    <h2>{name + age + height}</h2>
  )
}

// 父组件
export default class App extends Component {
  render() {
    return (
      <div>
        <ChildCpn name="hss" age="21" height="1.7" />
        <ChildCpn name="kobe" age="40" height="1.98" />
      </div>
    )
  }
}

子传父

函数传递

import React, { Component } from 'react';

// 子组件
class CounterButton extends Component {
  render() {
    const { onClick } = this.props;
    return <button onClick={onClick}>+1</button>
  }
}

// 父组件
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>
        <CounterButton onClick={e => this.increment()} name="why" />
      </div>
    )
  }

  increment() {
    this.setState({
      counter: this.state.counter + 1
    })
  }
}
React

最后更新于:2021-02-16 21:16:48

欢迎评论留言~
0/400
支持markdown
Comments | 0 条留言
按时间
按热度
目前还没有人留言~