React能否在另一组件的onClick监听事件中调用类组件?
核心错误1:事件回调中返回的JSX不会被React渲染
React 组件只有被包含在父组件render方法返回的JSX树中时,才会被实例化、执行生命周期逻辑和渲染。你在onClick回调中返回<Overlay />,这个生成的JSX对象没有被交给React处理,会被直接丢弃,自然不会触发Overlay组件的任何调用。
核心错误2:Overlay组件存在逻辑缺陷
不能在render()方法中执行异步请求并调用setState:render是纯函数,每次组件渲染都会执行,你在这里调用setState会触发重新渲染,进而再次执行异步请求、再次调用setState,最终形成无限渲染死循环。异步数据请求应当放在componentDidMount等生命周期钩子中执行。
修复代码
1. 修复TagListItem组件
通过组件状态控制Overlay的显隐,将Overlay放入render返回的JSX树中:
import React from "react"; import Overlay from "./Overlay"; export default class TagListItem extends React.Component { state = { showOverlay: false } render() { return( <div> <div className={'tag'} onClick={() => this.setState({showOverlay: true})}> {this.props.tag} </div> {this.state.showOverlay && <Overlay {...this.props} onClose={() => this.setState({showOverlay: false})} />} </div> ) } }
2. 修复Overlay组件
将异步请求移到componentDidMount生命周期中:
import React from "react"; import ImagesAndTags from "./ImagesAndTags"; export default class Overlay extends React.Component { constructor(props) { super(props); this.state = { manifest: [], } } componentDidMount() { const imagesAndTags = new ImagesAndTags(); imagesAndTags.getManifest(this.props.imageName, this.props.tag) .then(manifest => { this.setState({manifest: manifest}) }) } render() { return( <div className={'overlay'}> {this.state.manifest} <button onClick={this.props.onClose}>关闭</button> </div> ) } }
内容的提问来源于stack exchange,提问作者TraktorJack
相关产品推荐
相关产品推荐

