React 父组件传递 methods props 给子组件

挑战 React 第十七篇

在 React 第十一篇了解透过 element 传递 props,此篇要介绍要写传父组件里的方法给子组件

目标

子组件按了按钮,印出父组件传来的方法子组件传参数给父组件

实作步骤

新增一个 parent.js 档案在 parent.js 写一个按钮,按了会印出 Hello Parent
import React, { Component } from 'react'import Child from './Child'; class Parent extends Component {  constructor(props) {    super(props)      this.state = {       parentName: "parent"    }    // 需绑定 this,否则会找不到 hello method    this.hello = this.hello.bind(this);  }    hello() {    console.log(`Hello ${this.state.parentName}`);  }  render() {    return (      <div>         <button onClick={this.hello}>button</button>      </div>    )  }}export default Parent
试着 yarn start 前两步骤

确认按了按钮,有印出 Hello Parent

把 hello method 传递给子组件使用的写法
render() {    return (      <div>         // 把方法当作 element 传递下去给 Child 组件         <Child hello = {this.hello}/>      </div>    )  }
新增一个 child.js 档案
import React, { Component } from 'react'class Child extends Component {  render() {    return (      <div>        // 收到来自 parent 的 props,使用 hello method        <button onClick={this.props.hello}>button</button>      </div>    )  }}export default Child
yarn start 前五步骤

确认按了按钮,印出 Hello Parent
因此现在我们会用传递的方式拿到父组件的方法。

在子组件传参数给父组件

Parent.js 父组件

 hello(childName) {    console.log(`Hello ${this.state.parentName} from ${childName}`);  }

Child.js 子组件

 render() {    return (      <div>        // 传入参数 Child        <button onClick={() => this.props.hello('child')}>button</button>      </div>    )  }
yarn start 第七步骤

确认取得子组件传来的参数,并印出 Child

小结论

当初学会这个方式的时候,觉得很方便,在我们组内有时候也会透过这个写法达到某些目的,用 method 当作 props 这事情也是之后文章会常写的写法。


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章