React - 将道具传递给子onClick

r_c*_*ill 5 javascript reactjs

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

我在这里查看了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>

        );
    }
}
Run Code Online (Sandbox Code Playgroud)

TW8*_*000 5

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

  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} />
Run Code Online (Sandbox Code Playgroud)