React - 将props传递给孩子 onClick

IT技术 javascript reactjs
2021-05-18 18:40:16

我有一个从 Dropbox 中提取的图像和标题的索引。我的目标是能够单击标题并加载特定项目,但现在我只是试图掌握将单击标题的数据传递给 a 组件的方法。

我已经查看了 React 教程、文档和其他类似问题(我担心这将被视为重复问题),但我似乎无法找到传递单击的特定标题的方法. 我目前收到错误:无法读取 undefined 的属性“title”

我已经设法通过 console.log 拉出特定的标题,并用所有的标题填充了 ProjectTitle 组件,但我被这个看似简单的障碍难住了。

谢谢

class ProjectTitle extends React.Component{
    render() {
        return <h1>{this.props.title}</h1>;
    }
}

class Index extends React.Component {
    constructor(){
        super();
        this.state = {
            imageSource: [],
            imageTitles: [],
        }
    }

    componentWillMount(){
        …
    }

    render(){
        if(!this.state.imageSource.length)
            return null;
        let titles = this.state.imageTitles.map((el, i) => <p>{el}</p>)
        let images = this.state.imageSource.map((el, i) =>

        <div className="imageContainer">
            <img key={i} className='images' src={el}/>
            <div className="imageTitle" onClick={() => 
                ProjectTitle.props.title(titles[i].props.children)}>{titles[i]}
            </div>
        </div>
        )

        return (
            <div className="wrapper">
                {images}
                <ProjectTitle />
            </div>

        );
    }
}
1个回答

通常在这种情况下,您希望遵循以下结构:

  1. 单击事件处理程序设置一个状态属性,如activeTitle被单击的 id。
  2. 需要设置其 prop 的元素 ( ProjectTitle) 从它的父状态 ( Index) 中获取它

对代码的更改可能类似于:

// in Index constructor 
this.state = {
    // stuff you already have...
    activeTitle: null
}
this.handleItemClick = this.handleItemClick.bind(this);

// in Index
handleItemClick(title) {
    this.setState({activeTitle: title});
}

// in Index.render() in the loop
// you might have you add some code to get titles[i]
<div className="imageTitle" onClick={() => this.handleItemClick(titles[i])}></div>

// in Index.render() return statement
<ProjectTitle title={this.state.activeTitle} />