React开发中点击子组件时如何正确调用父组件内定义的方法
问题原因
changeColor是App类的实例方法,不是静态方法,你直接通过App.changeColor调用本质是在找App类的静态方法,自然会报方法不存在的错误。- React中父子组件通信的标准方案是通过props传递,而不是直接导入类调用方法,这样会严重耦合组件逻辑,也不符合React的单向数据流规则。
- 你原有类组件代码中
changeColor内this.props.bg = xxx的写法是错误的:props是只读属性,不允许直接赋值,要修改组件的渲染值需要通过state管理。
类组件版本修复方案
第一步:修改App.js
把changeColor方法通过props传递给ColorBox组件,如果需要单独修改被点击的盒子颜色,还需要把每个盒子的颜色放到state中管理,示例修改:
import React from 'react' import './App.css' import ColorBox from './ColorBox'; class App extends React.Component { state = { colorList: ["blue", "red", "yellow", "green", "purple", "indigo", "grey", "pink"], // 管理所有盒子的颜色 boxColors: Array.from({length:16}, () => this.randomizeColor()) } changeColor = (index) => { const newBoxColors = [...this.state.boxColors] newBoxColors[index] = this.randomizeColor() this.setState({boxColors: newBoxColors}) alert("修改成功") } randomizeColor() { const random = Math.floor(Math.random() * this.state.colorList.length); return this.state.colorList[random]; } render() { return ( <div className="App"> {this.state.boxColors.map((bg, index) => ( <ColorBox key={index} bg={bg} onClick={() => this.changeColor(index)} /> ))} </div> ) } } export default App
第二步:修改ColorBox.js
删掉对App的导入,直接使用props传递过来的方法:
import React from 'react' import './App.css' class ColorBox extends React.Component { render() { return ( <div className="color-box" onClick={this.props.onClick} style={{backgroundColor: this.props.bg}} > </div> ) } } export default ColorBox
函数式版本说明
你提供的函数式组件版本已经规避了跨组件调用方法的问题:所有逻辑都收拢在App组件内,生成颜色块的时候直接绑定changeColor方法,不需要单独拆分ColorBox组件的前提下可以直接正常运行。如果要拆分成独立的ColorBox组件,和类组件逻辑一致,把changeColor作为props传递给子组件即可。
内容的提问来源于stack exchange,提问作者Troublegum
相关产品推荐
相关产品推荐

