挑战 React 第十七篇
在 React 第十一篇了解透过 element 传递 props,此篇要介绍要写传父组件里的方法给子组件
。
目标
子组件按了按钮,印出父组件传来的方法子组件传参数给父组件实作步骤
新增一个 parent.js 档案在 parent.js 写一个按钮,按了会印出 Hello Parentimport 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
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 这事情也是之后文章会常写的写法。