【问题标题】:React - Passing props to child onClickReact - 将道具传递给子 onClick
【发布时间】:2017-08-23 21:14:33
【问题描述】:

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

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

我已经设法通过 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>

        );
    }
}

【问题讨论】:

  • 尝试将新的title 添加到state,然后更新该标题onclick。传递state.title 作为ProjectTitle 的道具
  • 您确定imageSources 的长度与imageTitles 的长度相同吗?
  • Tareq 的评论很有道理,如果设置了 activeTitle,您可能需要进行一些三元检查,然后渲染组件,否则渲染未定义

标签: javascript reactjs


【解决方案1】:

一般在这样的情况下,你要遵循这样的结构:

  1. Click 事件处理程序将像activeTitle 这样的状态属性设置为被点击的 id。
  2. 需要设置其属性的元素 (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} />

【讨论】:

    猜你喜欢
    • 2016-03-19
    • 2023-03-12
    • 2020-12-19
    • 1970-01-01
    • 2014-03-12
    • 2018-07-29
    • 2019-12-31
    • 2017-04-25
    • 1970-01-01
    相关资源
    最近更新 更多